From b3a860c1152da3ab47bae331bf22f2227ef94e26 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 17 Oct 2026 09:36:07 +0800 Subject: [PATCH] think-tags 0.1.1: a inside Markdown code no longer ends the stripped thinking (#176) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With "strip" on, a reply that opened with was cut at the first literal , even one the thinking wrote out as an example in inline code or a fenced block. Kane-Kuroneko's reply ("使用 `...` 标签") then began mid-sentence, as the gateway's own Chat decoder did before yetone/magpie d4a1b9baa (#2634). - findClose ports magpie's mdCode (internal/gateway/chat.go): is looked for only outside Markdown code. An inline span ends with its line, so a stray backtick can't swallow the answer, and a fence is a block. A run of backticks or a close split across chunks is held back. - Streamed (strip) and whole (stripWhole) replies both use it, for Chat, Anthropic and Responses. - A Chat stream that ends inside the block no longer gives held-back text to the answer: inside, that is thinking (a held "``" would have leaked; before, so would a held "…`. This mode takes that block out, so an agent doesn't keep it in its history and send it back every turn. - Only a block at the start of the text is taken out. A `` the model writes later, in code for example, stays. +- A `` inside the block in Markdown code (`` `` ``, or a fenced block) is part of the thinking, an example written out, not its end. - A tag split across streamed chunks is still found. - It works on Anthropic, Chat and Responses replies, streamed or whole. diff --git a/packages/think-tags/cases.json b/packages/think-tags/cases.json index ed2a8cc..d468afd 100644 --- a/packages/think-tags/cases.json +++ b/packages/think-tags/cases.json @@ -46,6 +46,20 @@ "ctx": { "protocol": "chat" }, "response": { "choices": [{ "message": { "content": "xHi" } }] }, "expect_response": { "choices": [{ "message": { "content": "Hi" } }] } }, + { "name": "strip: a in inline code is the thinking's words (#176)", + "ctx": { "protocol": "chat", "stream": true }, + "events": [ + { "data": { "choices": [{ "index": 0, "delta": { "content": "开始分析。使用 `...` 标签。\n继续分析。\n最终正文。" } }] } }], + "expect_events": [ + { "choices": [{ "index": 0, "delta": { "content": "" } }] }, + { "choices": [{ "index": 0, "delta": { "content": "" } }] }, + { "choices": [{ "index": 0, "delta": { "content": "最终正文。" } }] }] }, + { "name": "strip: a whole reply's close in inline code (#176)", + "ctx": { "protocol": "chat" }, + "response": { "choices": [{ "message": { "content": "开始分析。使用 `...` 标签。\n继续分析。\n最终正文。" } }] }, + "expect_response": { "choices": [{ "message": { "content": "最终正文。" } }] } }, { "name": "to_content: reasoning_content into the text", "ctx": { "protocol": "chat", "stream": true }, "options": { "mode": "to_content" }, diff --git a/packages/think-tags/package.json b/packages/think-tags/package.json index ab76305..d85e231 100644 --- a/packages/think-tags/package.json +++ b/packages/think-tags/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/middleware-think-tags", - "version": "0.1.0", + "version": "0.1.1", "description": "Take a model's … out of its reply's text, or put a Chat reply's reasoning_content into it (New API's thinking_to_content), as magpie gateway middleware", "type": "module", "files": ["think-tags.middleware.js", "README.md"], diff --git a/packages/think-tags/think-tags.middleware.js b/packages/think-tags/think-tags.middleware.js index c96dec4..5973d7e 100644 --- a/packages/think-tags/think-tags.middleware.js +++ b/packages/think-tags/think-tags.middleware.js @@ -8,7 +8,10 @@ // … at the start of its text has that block taken out, so // an agent doesn't keep it in its history and send it back each turn. Only // a block that opens the text is taken; later on, in code the model -// writes, stays. Anthropic, Chat and Responses replies, streamed or whole. +// writes, stays. Within the block, a in Markdown code (an inline +// span, or a fenced block) is the thinking's words, an example written out, +// not its end (magpie-community/plugins#176, as magpie's gateway reads it +// since #2634). Anthropic, Chat and Responses replies, streamed or whole. // // "to_content": a Chat reply's reasoning_content (or reasoning) is put in // its text as …, for a client that shows only the text. @@ -47,8 +50,9 @@ export function onEvent(ev, ctx) { changed = true } } - // a stream that ends while text is held back gives it back - if (c.finish_reason && st["c" + c.index] && st["c" + c.index].carry) { + // a stream that ends while text is held back gives it back; what is + // held inside the block is thinking, and stays out + if (c.finish_reason && st["c" + c.index] && st["c" + c.index].carry && !st["c" + c.index].inside) { c.delta.content = (c.delta.content || "") + st["c" + c.index].carry st["c" + c.index].carry = "" changed = true @@ -111,17 +115,64 @@ function stripItem(it) { return true } -// stripWhole takes a think block off the start of a whole text +// stripWhole takes a think block off the start of a whole text: up to its +// first outside Markdown code function stripWhole(t) { - const m = /^\s*[\s\S]*?<\/think>\s*/.exec(t) - return m ? t.slice(m[0].length) : t + const lead = /^\s*/.exec(t)[0] + if (!t.startsWith(OPEN, lead.length)) return t + const rest = t.slice(lead.length + OPEN.length) + const [at] = findClose({ span: 0, fence: 0, mid: false }, rest, true) + return at < 0 ? t : rest.slice(at + CLOSE.length).replace(/^\s+/, "") +} + +// findClose gives where is first outside Markdown code in s, read +// on from the pieces before (m: the open inline span's backticks, the open +// fence's, and whether the line is past its leading spaces), or -1 and how +// much of the end of s to hold back for the next piece: a close tag or a +// run of backticks that may go on there. Unless last; then nothing is +// held. An inline span is taken to end with its line, so a stray backtick +// can't swallow the answer. magpie's mdCode (internal/gateway/chat.go). +function findClose(m, s, last) { + for (let j = 0; j < s.length; ) { + const c = s[j] + if (c === "`") { + let k = j + while (k < s.length && s[k] === "`") k++ + if (k === s.length && !last) return [-1, s.length - j] + const n = k - j + if (m.fence > 0) { + if (!m.mid && n >= m.fence) m.fence = 0 + } else if (m.span > 0) { + if (n === m.span) m.span = 0 + } else if (!m.mid && n >= 3) m.fence = n + else m.span = n + m.mid = true + j = k + } else if (c === "\n") { + m.span = 0 + m.mid = false + j++ + } else if (c === " " || c === "\t") { + j++ + } else if (c === "<" && m.span === 0 && m.fence === 0) { + if (s.startsWith(CLOSE, j)) return [j, 0] + if (!last && CLOSE.startsWith(s.slice(j))) return [-1, s.length - j] + m.mid = true + j++ + } else { + m.mid = true + j++ + } + } + return [-1, 0] } // strip is a stream's text, a piece at a time, without a think block at // its start. Its state, by stream: inside the block, text held back that -// may be the start of a tag, whether the text has begun. +// may be the start of a tag (or, inside, a run of backticks), whether the +// text has begun, and where the block is in Markdown code. function strip(state, key) { - const st = state[key] || (state[key] = { inside: false, carry: "", begun: false, trim: false }) + const st = state[key] || (state[key] = { inside: false, carry: "", begun: false, trim: false, code: { span: 0, fence: 0, mid: false } }) return (piece) => { if (st.begun) return piece let s = st.carry + piece @@ -129,9 +180,9 @@ function strip(state, key) { let out = "" for (;;) { if (st.inside) { - const i = s.indexOf(CLOSE) + const [i, hold] = findClose(st.code, s, false) if (i < 0) { - st.carry = tail(s, CLOSE) + st.carry = hold ? s.slice(s.length - hold) : "" return out } s = s.slice(i + CLOSE.length) @@ -164,12 +215,6 @@ function strip(state, key) { } } -// tail is the end of s that may begin tag -function tail(s, tag) { - for (let n = Math.min(tag.length - 1, s.length); n > 0; n--) if (tag.startsWith(s.slice(s.length - n))) return s.slice(s.length - n) - return "" -} - // reasoningToText moves a Chat chunk's reasoning into its text, opening // on the first and closing it when the text or the end comes. function reasoningToText(ev, state) { diff --git a/packages/think-tags/think-tags.test.mjs b/packages/think-tags/think-tags.test.mjs index 295c2b9..a192b9f 100644 --- a/packages/think-tags/think-tags.test.mjs +++ b/packages/think-tags/think-tags.test.mjs @@ -1,4 +1,83 @@ import * as mod from "./think-tags.middleware.js" import { check } from "../../scripts/middleware.mjs" +import { expect, test } from "bun:test" check(import.meta.dir, mod) + +// #176: the reply in Kane-Kuroneko's yetone/magpie#2634, as its bytes were +// (magpie's internal/gateway/think_code_test.go): thinking that writes the +// close tag out as an inline-code example, then the answer. +const exampleClose = "开始分析。使用 `...` 标签。\n继续分析。\n最终正文。" + +// streamed runs text through strip as a Chat stream of the given deltas, +// then a finish, and gives back the text that came out +function streamed(parts) { + const ctx = { protocol: "chat", stream: true, options: {}, state: {} } + let out = "" + const evs = parts.map((p) => ({ choices: [{ index: 0, delta: { content: p } }] })) + evs.push({ choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }) + for (const ev of evs) { + const r = mod.onEvent(ev, ctx) ?? ev + out += r.choices[0].delta.content ?? "" + } + return out +} + +// anthropic is streamed for an Anthropic stream's text deltas +function anthropic(parts) { + const ctx = { protocol: "anthropic", stream: true, options: {}, state: {} } + let out = "" + for (const p of parts) { + const ev = { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: p } } + out += (mod.onEvent(ev, ctx) ?? ev).delta.text + } + return out +} + +const chars = (s) => Array.from(s) +// a byte a delta: each UTF-8 byte its own piece (as a Latin-1 character), +// read back as UTF-8 once joined +const bytes = (s) => Array.from(new TextEncoder().encode(s), (b) => String.fromCharCode(b)) +const utf8 = (s) => new TextDecoder().decode(Uint8Array.from(s, (c) => c.charCodeAt(0))) + +test("#176: a in inline code doesn't end the block, whole", () => { + expect(streamed([exampleClose])).toBe("最终正文。") + expect(anthropic([exampleClose])).toBe("最终正文。") + const ctx = { protocol: "chat", options: {}, state: {}, status: 200 } + expect(mod.onResponse({ choices: [{ message: { content: exampleClose } }] }, ctx).choices[0].message.content).toBe("最终正文。") + expect(mod.onResponse({ content: [{ type: "text", text: exampleClose }] }, ctx).content[0].text).toBe("最终正文。") + expect(mod.onResponse({ output: [{ type: "message", content: [{ type: "output_text", text: exampleClose }] }] }, ctx).output[0].content[0].text).toBe("最终正文。") +}) + +test("#176: a character a delta", () => { + expect(streamed(chars(exampleClose))).toBe("最终正文。") + expect(anthropic(chars(exampleClose))).toBe("最终正文。") +}) + +test("#176: a byte a delta", () => { + expect(utf8(streamed(bytes(exampleClose)))).toBe("最终正文。") + expect(utf8(anthropic(bytes(exampleClose)))).toBe("最终正文。") +}) + +// magpie's TestChatThinkCloseInCode, the answer each leaves +const more = [ + ["a double-backtick span", ["a ``x``` bc"], "c"], + ["a fenced block", chars("like\n```xml\n\n```\nso\nok"), "ok"], + ["a span ends with its line", ["a `b\n\nok"], "ok"], + ["backticks after the close", chars("a\n`x` y"), "`x` y"], + ["a close tag split by a chunk", ["a `", "x` bc"], "c"], + ["backticks held at the end stay thinking", ["a ``"], ""], +] +for (const [name, parts, want] of more) { + test(name, () => { + expect(streamed(parts)).toBe(want) + expect(anthropic(parts)).toBe(want) + }) +} + +test("a whole reply with a close only in code keeps its text", () => { + const ctx = { protocol: "chat", options: {}, state: {}, status: 200 } + const t = "use `` here" + expect(mod.onResponse({ choices: [{ message: { content: t } }] }, ctx)).toBeUndefined() + expect(mod.onResponse({ choices: [{ message: { content: "like\n```\n\n```\n\n\nok" } }] }, ctx).choices[0].message.content).toBe("ok") +})