From 7ea8aeaba7d15a63ccd1e5ecb5f9f4f4a6239733 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 17 Oct 2026 03:45:01 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20DSML=20written=20with=20a=20run=20of?= =?UTF-8?q?=20pipes=20(<=EF=BD=9C=EF=BD=9CDSML=EF=BD=9C=EF=BD=9Cinvoke)=20?= =?UTF-8?q?is=20made=20the=20call=20too,=20not=20left=20as=20text=20(#2623?= =?UTF-8?q?,=20OKURBITO)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DeepSeek wrote its tool call as <||DSML||invoke name="get_weather">… (two full-width pipes each side) and the reply reached the Responses client as that markup: textCallAt only knew the one-pipe marks, so nothing was held and parseTextCalls, whose regexes already read a run of pipes, never ran. dsmlMark now finds a DSML tag's mark as the parse regexes (dsmlTag) read one, with no list of spellings: <, spaces, / and spaces for a close, a pipe, a run of pipes and spaces, DSML, and another run that may be empty. A pipe is ASCII | or full-width |, in any number and any mix of widths. textCallAt uses it to find a call and to hold a mark still being written (down to a full-width pipe's first bytes); cutMark uses it to trim a tag cut short at the end, once the tag has begun its pipes, so a value ending "a < " keeps its "<". Every route goes through these: textCallSee (translations), textCallTidy (relayed Chat streams) and wholeTextCalls (whole Chat replies). OKURBITO pointed out on the issue that a spelling table leaves |||, ||, || and the like as text; this reads the class. Tests (textcalls_pipes_test.go). Which cases were seen and which were made up, as OKURBITO set out on the issue: one reply was written by a model on its own in real use (deepseek-flash offered web_search: <||DSML|| calls> … <||DSML|| invoke name="web_search"> …), kept byte for byte as observedPipes; the issue's get_weather reply came from asking the model to echo the markup; every other spelling (three pipes, ASCII, widths that disagree, spaces after <, no pipes after DSML) is constructed and has not been seen. - TestTextWrittenDSMLDoublePipe: the observed reply, relayed Chat streamed and whole, is a web_search call with its query and no DSML left; the issue's reply through /v1/responses, streamed and whole, and a whole Chat reply, is a get_weather call with {"city":"Beijing"} and no message item. - TestTextWrittenDSMLAnyPipes: | | || || || || ||| ||| "| |", each reply sent one character per chunk: the call, wrapped with text before, a space before invoke (the live <||DSML|| invoke), no parameters, cut short, tags only with the last cut short, a tool not offered, a mark's start at the end, pipes without DSML; each ends as the one-pipe reply. - TestTextWrittenDSMLDoublePipeEveryCut: the reply split at every byte boundary JSON allows is the same call; textCallAt holds each prefix of the mark, a full-width pipe's first bytes too. - TestTextWrittenDSMLMarkAsParsed: widths that disagree within a tag and between its open and close, spaces after < and around /, no pipes after DSML are each the call; a cut-short value ending in "a < " keeps it; "x < y and a <" stays text. Fails without the change: with b7d9616d0's textcalls.go all four FAIL, the observed reply among them ("text \"<||DSML||invoke …\" calls map[] finish \"stop\"", "a message item beside the call"; MarkAsParsed's widths that disagree, spaces after <, no pipes after DSML); the one-pipe rows pass there. With an earlier draft of dsmlMark (a run of pipes, none after <, one required after DSML) MarkAsParsed FAILs its spaces-after-< and no-pipes-after-DSML rows; with cutMark's has-begun-its-pipes guard taken out it FAILs the cut-short value ("a " for "a < "). Not tried against a real DeepSeek upstream: the fixtures are the bytes OKURBITO posted. In the observed event the request offered only a hosted web_search ({"type":"web_search"}), not a function; a call to a tool the request didn't offer by name still goes on as text, as before, and the test offers web_search as a function. Run with both #2623's and #2625's changes, on b7d9616d0 (macOS, Go 1.26.8, load average 80-270 from other sessions): - gofmt -l: nothing. go vet -tags nogui ./... with GOOS darwin, linux and windows: clean. - set -o pipefail; go test -timeout 45m ./...: every package ok except internal/agent (2702s) and internal/gateway (2721s), which ran past 45m under the load (#2544, #2108; no test hung, each was seconds into its run). Rerun with -timeout 90m: internal/agent ok (2816s); internal/gateway's only red is TestDesktopSubagentUnsetDoesNotDecode, "allocated 1 times" (10/10 green alone, filed as #2699). The textcalls tests passed in that run. --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/textcalls.go | 97 ++++++++++++- internal/gateway/textcalls_pipes_test.go | 176 +++++++++++++++++++++++ 3 files changed, 271 insertions(+), 4 deletions(-) create mode 100644 internal/gateway/textcalls_pipes_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 620090f68..a8fba1341 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -152,7 +152,7 @@ recorded as a prediction failure (`noPrediction`). - 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' `{…}`, DeepSeek's DSML (`<|DSML|invoke name=…>` with its parameters), DeepSeek's half-Hermes `` form (#917) and GLM's ``/`` (#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`. +- 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' `{…}`, DeepSeek's DSML (`<|DSML|invoke name=…>` with its parameters; its mark found as the parse regexes read it, by `dsmlMark`, not from a list of spellings: any run of pipes, ASCII or full-width or mixed, spaces after `<` and around `/`, `<||DSML||` too, #2623), DeepSeek's half-Hermes `` form (#917) and GLM's ``/`` (#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. A model may still wrap its JSON answer in a Markdown code fence; a client that asked for structured output, in a field or told in the system prompt (`wantsJSON`), gets the JSON inside a single unlabelled or json-labelled fence when that content is a complete valid JSON value, streamed (`fenceEncoder`) or whole (`unfencedResult`), in [`format_fence.go`](../../internal/gateway/format_fence.go). Invalid or truncated JSON, other fence languages, text outside the fence, and answers to plain-text clients reach the client as they came. This normalization applies to translated replies; native protocol passthrough stays byte-preserving. - A tool's images reach the model on every translation (`toolOutput` in [`ir.go`](../../internal/gateway/ir.go) reads them from Anthropic's `tool_result`, Responses' `function_call_output`, such as Codex's `view_image` output `[{"type":"input_image","image_url":"data:…"}]`, and a Chat tool message). Anthropic's Messages keeps them in the `tool_result`. Chat, Qoder and Cursor (`cursorImage`) put them in a user message right after the results, and the result says they follow. Command Code puts them in the user's turn after the results, Gemini and Code Assist after the function's response, and Devin in its tool message. Kiro's results hold text alone, so Kiro (the built-in, and its plugin from 0.1.9 on) sends them with the message that answers the call, and only the latest images go again (#369, #1861). `TestCodexToolImageReachesAnthropicPlugin`, `TestCodexToolImageKiro`, `TestCodexToolImageCursor`, and the plugin's `tool-images.test.mjs`. - Group members are `provider/model[:effort]`. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671). diff --git a/internal/gateway/textcalls.go b/internal/gateway/textcalls.go index 2afc2c147..2370020ac 100644 --- a/internal/gateway/textcalls.go +++ b/internal/gateway/textcalls.go @@ -24,8 +24,76 @@ import ( // real tool call, and the reply ends as one that called tools. Held text // that isn't all such blocks goes on as the text it was. -// textCallMarks are what a call written into the text opens with. -var textCallMarks = []string{"", "<|DSML|", "<|DSML|"} +// textCallMarks are what a call written into the text opens with, beside +// DeepSeek's DSML tags, which dsmlMark reads. +var textCallMarks = []string{""} + +// dsmlMark tells whether s begins with a DSML tag's mark, read as the +// parse regexes read one (dsmlTag): <, spaces, / and spaces for a close +// when closing is true, a pipe, then a run of pipes and spaces, DSML and +// another run, which may be empty. A pipe is ASCII | or full-width |, in +// any number and any mix of widths: DeepSeek writes one or two +// (#2623, OKURBITO: <||DSML||invoke went out as text), and its widths +// don't always agree within a tag, so no spelling is listed. n is the +// mark's length when s begins with one; more is whether s, too short for +// one, could be one's beginning still being written, down to a full-width +// pipe's first bytes. +func dsmlMark(s string, closing bool) (n int, more bool) { + if !strings.HasPrefix(s, "<") { + return 0, false + } + i := 1 + space := func() { + for i < len(s) && strings.ContainsRune(" \t\r\n", rune(s[i])) { + i++ + } + } + // pipe steps over one pipe at i; part is whether s ends in the first + // bytes of a full-width one + pipe := func() (ok, part bool) { + switch { + case i < len(s) && s[i] == '|': + i++ + return true, false + case strings.HasPrefix(s[i:], "|"): + i += len("|") + return true, false + } + return false, i < len(s) && strings.HasPrefix("|", s[i:]) + } + // run reads pipes and spaces from i; part as for pipe + run := func() (part bool) { + for { + space() + if ok, part := pipe(); !ok { + return part + } + } + } + space() + if closing && i < len(s) && s[i] == '/' { + i++ + space() + } + if i == len(s) { + return 0, true + } + if ok, part := pipe(); !ok { + return 0, part + } + if run() || i == len(s) { + return 0, true + } + if rest := s[i:]; !strings.HasPrefix(rest, "DSML") { + return 0, strings.HasPrefix("DSML", rest) + } + i += len("DSML") + if run() || i == len(s) { + // the run after DSML may go on in the next chunk + return 0, true + } + return i, false +} // writtenCall is one call read out of the text. type writtenCall struct { @@ -92,6 +160,21 @@ func textCallAt(s string) (at, tail int) { at = i } } + for i := strings.IndexByte(s, '<'); i >= 0 && (at < 0 || i < at); { + n, more := dsmlMark(s[i:], false) + if n > 0 { + at = i + break + } + if more && tail == 0 { + tail = len(s) - i + } + j := strings.IndexByte(s[i+1:], '<') + if j < 0 { + break + } + i += 1 + j + } if at >= 0 { return at, 0 } @@ -162,13 +245,21 @@ func parseTextCalls(s string, names map[string]bool) (calls []writtenCall, rest // cutMark is the end of s that is a mark's beginning cut short (), "" when there's none; a lone < may be text. func cutMark(s string) string { - for _, m := range append([]string{"", "", "", ""}, textCallMarks...) { for n := len(m) - 1; n >= 2; n-- { if strings.HasSuffix(s, m[:n]) { return m[:n] } } } + // a DSML tag's, open or close, however many its pipes; a run of + // them holds no <, so only the last can be one cut short. It has + // begun its pipes (a full-width one's first bytes too): "x < " is text + if i := strings.LastIndexByte(s, '<'); i >= 0 && strings.IndexAny(s[i:], "||\xef") >= 0 { + if _, more := dsmlMark(s[i:], true); more { + return s[i:] + } + } return "" } diff --git a/internal/gateway/textcalls_pipes_test.go b/internal/gateway/textcalls_pipes_test.go new file mode 100644 index 000000000..ab2f4db88 --- /dev/null +++ b/internal/gateway/textcalls_pipes_test.go @@ -0,0 +1,176 @@ +package gateway + +import ( + "strings" + "testing" + "unicode/utf8" +) + +// Which of these were seen and which were made up (OKURBITO on #2623): +// - observedPipes is the one reply a model wrote on its own, in real +// use: deepseek-flash, offered web_search, wrote the call as text with +// two full-width pipes and a space before each tag's name; +// - issuePipes is the issue's reproduction: the model was asked to echo +// those bytes back (workbuddy/deepseek-v4.1-flash from a Responses +// client), and the reply it got came back as text; +// - every other spelling below (three pipes, ASCII, widths that +// disagree, spaces after <, no pipes after DSML) is constructed: no +// one has seen a model write it. They are here because the mark is +// read as the parse reads it, not from a list of spellings. +const observedPipes = "<||DSML|| calls>\n<||DSML|| invoke name=\"web_search\">\n<||DSML|| parameter name=\"query\" string=\"true\">current Python version latest stable release\n\n" + +const issuePipes = `<||DSML||invoke name="get_weather"><||DSML||parameter name="city" string="true">Beijing` + +const weatherTool = `"tools":[{"type":"function","name":"get_weather","description":"Get the weather of a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]` + +// #2623: DSML written with two pipes went to a Responses client as text, +// the issue's prompted reply, +// streamed or whole, while one pipe of either width was made the call. +func TestTextWrittenDSMLDoublePipe(t *testing.T) { + // the reply seen in real use, its bytes as they came: a function + // web_search offered, it is the call, the calls wrapper gone with it + for _, stream := range []string{"true", "false"} { + body := `{"model":"a/m","stream":` + stream + `,"messages":[{"role":"user","content":"You MUST call the web_search tool first"}],"tools":[{"type":"function","function":{"name":"web_search","parameters":{"type":"object","properties":{"query":{"type":"string"}}}}}]}` + var text *string + var calls map[string]string + var finish, raw string + if stream == "true" { + var s string + s, calls, finish, raw = relayedChat(t, body, chunkOf(observedPipes), stopChunk) + text = &s + if s == "" { + text = nil + } + } else { + var cs []wholeCall + text, cs, finish, raw = wholeChat(t, body, "application/json", wholeChatUp(observedPipes)) + calls = map[string]string{} + for _, c := range cs { + calls[c.Function.Name] = c.Function.Arguments + } + } + if text != nil || len(calls) != 1 || calls["web_search"] != `{"query":"current Python version latest stable release"}` || finish != "tool_calls" || strings.Contains(raw, "DSML") { + t.Fatalf("observed, stream=%s: text %q calls %v finish %q\n%s", stream, strOr(text), calls, finish, raw) + } + } + + for _, stream := range []string{"true", "false"} { + items, raw := responsesItems(t, `{"model":"a/m","stream":`+stream+`,"input":"weather","max_output_tokens":1200,`+weatherTool+`}`, + chunkOf(issuePipes), stopChunk) + var call map[string]any + for _, it := range items { + switch it["type"] { + case "function_call": + call = it + case "message": + t.Errorf("stream=%s: a message item beside the call: %v", stream, it) + } + } + if call == nil || call["name"] != "get_weather" || call["arguments"] != `{"city":"Beijing"}` || strings.Contains(raw, "DSML") { + t.Fatalf("stream=%s: %v\n%s", stream, call, raw) + } + } + text, calls, finish, raw := wholeChat(t, `{"model":"a/m","stream":false,"messages":[{"role":"user","content":"weather"}],`+chatWeatherTool+`}`, + "application/json", wholeChatUp(issuePipes)) + if text != nil || len(calls) != 1 || calls[0].Function.Name != "get_weather" || calls[0].Function.Arguments != `{"city":"Beijing"}` || + finish != "tool_calls" || strings.Contains(raw, "DSML") { + t.Fatalf("whole: text %q calls %+v finish %q\n%s", strOr(text), calls, finish, raw) + } +} + +const chatWeatherTool = `"tools":[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}}]` + +// Every spelling of DSML's pipes is read as the one-pipe spelling is: a +// run of them, ASCII or full-width or both, with spaces between, as +// DeepSeek wrote <||DSML|| invoke in a live session. Each reply goes +// up one character to a chunk, so a mark is always cut across chunks; a +// reply that names no offered tool, is cut short, is empty or only looks +// like a mark ends as the one-pipe reply ends. +func TestTextWrittenDSMLAnyPipes(t *testing.T) { + body := `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"weather"}],` + chatWeatherTool + `}` + // written with | standing for the pipes; text, call and finish are + // what the one-pipe reply gives + cases := []struct{ name, reply, text, args, finish string }{ + {"the issue's", strings.ReplaceAll(issuePipes, "||", "|"), "", `{"city":"Beijing"}`, "tool_calls"}, + {"wrapped, text before", "Checking.\n\n<|DSML|function_calls>\n<|DSML|invoke name=\"get_weather\">\n<|DSML|parameter name=\"city\" string=\"true\">Beijing\n\n", "Checking.\n\n", `{"city":"Beijing"}`, "tool_calls"}, + {"a space before invoke", "<|DSML| invoke name=\"get_weather\">\n<|DSML| parameter name=\"city\" string=\"true\">Beijing\n", "", `{"city":"Beijing"}`, "tool_calls"}, + {"no parameters", "<|DSML|invoke name=\"get_weather\">", "", `{}`, "tool_calls"}, + {"cut short", "<|DSML|invoke name=\"get_weather\"><|DSML|parameter name=\"city\" string=\"true\">Beij", "", `{}`, "tool_calls"}, + {"tags only, the last cut short", "<|DSML|function_calls>\n\n\n<|DSML| parameter name=\"query\">x\n", "<|DSML| invoke name=\"web_search\">\n<|DSML| parameter name=\"query\">x\n", "", "stop"}, + {"a mark's start at the end", "a <|DS", "a <|DS", "", "stop"}, + {"pipes and no DSML", "a <| b |> c", "a <| b |> c", "", "stop"}, + } + for _, pipes := range []string{"|", "|", "||", "||", "||", "||", "|||", "|||", "| |"} { + for _, c := range cases { + spell := func(s string) string { return strings.ReplaceAll(s, "|", pipes) } + var up []string + for _, r := range spell(c.reply) { + up = append(up, chunkOf(string(r))) + } + text, calls, finish, raw := relayedChat(t, body, append(up, stopChunk)...) + var want map[string]string + if c.args != "" { + want = map[string]string{"get_weather": c.args} + } + if text != spell(c.text) || finish != c.finish || len(calls) != len(want) || calls["get_weather"] != want["get_weather"] { + t.Errorf("%q %s: text %q calls %v finish %q\n%s", pipes, c.name, text, calls, finish, raw) + } + } + } +} + +// The issue's reply, cut anywhere and its parts sent as chunks of their +// own, is the same call at every cut, a full-width pipe's bytes too. +func TestTextWrittenDSMLDoublePipeEveryCut(t *testing.T) { + body := `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"weather"}],` + chatWeatherTool + `}` + s := "Sure.\n" + issuePipes + for i := 1; i < len(s); i++ { + if !utf8.ValidString(s[:i]) { + continue // a chunk's JSON carries whole characters only + } + text, calls, finish, raw := relayedChat(t, body, chunkOf(s[:i]), chunkOf(s[i:]), stopChunk) + if text != "Sure.\n" || calls["get_weather"] != `{"city":"Beijing"}` || finish != "tool_calls" { + t.Fatalf("cut at %d: text %q calls %v finish %q\n%s", i, text, calls, finish, raw) + } + } + // and the scanner, which may see a character's first bytes alone + for i := 1; i < len("<||DSML|"); i++ { + at, tail := textCallAt("x" + issuePipes[:i]) + if at >= 0 || tail != i { + t.Fatalf("%q: at %d tail %d, want the %d bytes held", issuePipes[:i], at, tail, i) + } + } + if at, _ := textCallAt("x" + issuePipes); at != 1 { + t.Fatalf("the whole mark: at %d", at) + } +} + +// The mark is found as the parse reads it, not from a list of spellings +// (OKURBITO on #2623): widths that differ within a tag and between its +// open and close, spaces after < and around /, no pipes after DSML. A +// reply ending in a < that starts no pipes keeps it. +func TestTextWrittenDSMLMarkAsParsed(t *testing.T) { + body := `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"weather"}],` + chatWeatherTool + `}` + for _, c := range []struct{ name, reply, text, args string }{ + {"widths that disagree", `<||DSML||invoke name="get_weather"><||DSML||parameter name="city" string="true">Beijing`, "", `{"city":"Beijing"}`}, + {"spaces after < and around /", `< |DSML|invoke name="get_weather">< |DSML|parameter name="city" string="true">Beijing< / |DSML|parameter>`, "", `{"city":"Beijing"}`}, + {"no pipes after DSML", `<|DSMLinvoke name="get_weather"><|DSMLparameter name="city" string="true">Beijing`, "", `{"city":"Beijing"}`}, + {"a value ending in <", `<|DSML|invoke name="get_weather"><|DSML|parameter name="city" string="true">a < `, "", `{"city":"a \u003c "}`}, + {"a cut-short value ending in <", "{\"name\":\"get_weather\">\na < ", "", `{"city":"a \u003c "}`}, + {"text with < and no mark", "x < y and a <", "x < y and a <", ""}, + } { + var up []string + for _, r := range c.reply { + up = append(up, chunkOf(string(r))) + } + text, calls, finish, raw := relayedChat(t, body, append(up, stopChunk)...) + want, wantFinish := 1, "tool_calls" + if c.args == "" { + want, wantFinish = 0, "stop" + } + if text != c.text || finish != wantFinish || len(calls) != want || calls["get_weather"] != c.args { + t.Errorf("%s: text %q calls %v finish %q\n%s", c.name, text, calls, finish, raw) + } + } +}