think-tags 0.1.1: a </think> inside Markdown code no longer ends the stripped thinking (#176)

With "strip" on, a reply that opened with <think> was cut at the first
literal </think>, even one the thinking wrote out as an example in
inline code or a fenced block. Kane-Kuroneko's reply ("使用
`<think>...</think>` 标签") 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): </think> 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 "</th").

Run at fc9cf6a + this change:
- packages/think-tags `bun test`: 18 pass, 0 fail. New: the reporter's
  bytes (think_code_test.go's exampleClose) whole (Chat/Anthropic stream,
  Chat/Anthropic/Responses whole), one character a delta, one UTF-8 byte
  a delta; mdCode's other cases (double-backtick span, fence, span ends
  with its line, split close, held backticks); two cases.json cases so
  moejs checks it too.
- Against fc9cf6a's middleware: 6 of the new tests fail. With code state
  ignored (any "<" checked): the same 6 fail. With held text given back
  inside the block: "backticks held at the end stay thinking" fails.
- Whole repo, HOME=$(mktemp -d) bun test: 1698 pass, 0 fail on two runs.
  A first run had 1 fail whose name I didn't capture; two reruns were
  green, so it is unidentified, not fixed.
- bun scripts/check.mjs: exit 0.
Not run: a real model through magpie with the plugin installed.
This commit is contained in:
yetone
2026-10-17 09:36:07 +08:00
parent fc9cf6a7b0
commit b3a860c115
5 changed files with 156 additions and 17 deletions
+1
View File
@@ -13,6 +13,7 @@ Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @m
**`strip`** (the default). Some models (open reasoning models served by vLLM, Ollama and many relays) write their thinking into the reply as `<think>…</think>`. 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 `<think>` the model writes later, in code for example, stays.
- A `</think>` inside the block in Markdown code (`` `</think>` ``, 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.
+14
View File
@@ -46,6 +46,20 @@
"ctx": { "protocol": "chat" },
"response": { "choices": [{ "message": { "content": "<think>x</think>Hi" } }] },
"expect_response": { "choices": [{ "message": { "content": "Hi" } }] } },
{ "name": "strip: a </think> in inline code is the thinking's words (#176)",
"ctx": { "protocol": "chat", "stream": true },
"events": [
{ "data": { "choices": [{ "index": 0, "delta": { "content": "<think>开始分析。使用 `<think>...</th" } }] } },
{ "data": { "choices": [{ "index": 0, "delta": { "content": "ink>` 标签。\n继续分析。</th" } }] } },
{ "data": { "choices": [{ "index": 0, "delta": { "content": "ink>\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": "<think>开始分析。使用 `<think>...</think>` 标签。\n继续分析。</think>\n最终正文。" } }] },
"expect_response": { "choices": [{ "message": { "content": "最终正文。" } }] } },
{ "name": "to_content: reasoning_content into the text",
"ctx": { "protocol": "chat", "stream": true },
"options": { "mode": "to_content" },
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/middleware-think-tags",
"version": "0.1.0",
"version": "0.1.1",
"description": "Take a model's <think>…</think> 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"],
+61 -16
View File
@@ -8,7 +8,10 @@
// <think>…</think> 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; <think> later on, in code the model
// writes, stays. Anthropic, Chat and Responses replies, streamed or whole.
// writes, stays. Within the block, a </think> 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 <think>…</think>, 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 </think> outside Markdown code
function stripWhole(t) {
const m = /^\s*<think>[\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 </think> 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
// <think> on the first and closing it when the text or the end comes.
function reasoningToText(ev, state) {
+79
View File
@@ -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 = "<think>开始分析。使用 `<think>...</think>` 标签。\n继续分析。</think>\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 </think> 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", ["<think>a ``x`</think>`` b</think>c"], "c"],
["a fenced block", chars("<think>like\n```xml\n</think>\n```\nso</think>\nok"), "ok"],
["a span ends with its line", ["<think>a `b\n</think>\nok"], "ok"],
["backticks after the close", chars("<think>a</think>\n`x` y"), "`x` y"],
["a close tag split by a chunk", ["<think>a `", "x` b</th", "ink>c"], "c"],
["backticks held at the end stay thinking", ["<think>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 = "<think>use `</think>` here"
expect(mod.onResponse({ choices: [{ message: { content: t } }] }, ctx)).toBeUndefined()
expect(mod.onResponse({ choices: [{ message: { content: "<think>like\n```\n</think>\n```\n</think>\n\nok" } }] }, ctx).choices[0].message.content).toBe("ok")
})