think-tags 0.1.2: strip also takes a leading <thinking> or <thought> block, each ended by its own close tag (#777)
strip matched only <think>, so a model that opens its reply with
<thinking>…</thinking> (or <thought>…</thought>) kept that block in the
agent's history through this middleware, while magpie's own gateway
reads all three since e1d4dca96 (yetone/magpie#5106). The three tags
are now one map, as magpie's thoughtTags: a block at the start of the
text only, ended by its own close tag outside Markdown code, so a
</think> inside a <thinking> block is the thinking's words. A stream
holds back a lead that may still become any of the three (<think is
the start of both <think> and <thinking>). to_content still writes
<think>. The package, root README and registry summaries name the three
tags.
Run (mote, Bun 1.4.2, sandbox HOME): bun test packages/think-tags 37
pass, 0 fail; bun scripts/check.mjs ok; whole-repo bun test 6205 pass, 0 fail at origin/main 10a61c2e.
Broken by hand: the map back to <think> alone, 12 fail; the close tag
fixed to </think>, 11 fail; the stream's wait only for a <think> lead,
3 fail (split <thought> and one character a delta).
Not tried: a live model that sends <thinking>. npm: 0.1.1 never
published (plugins#180), so 0.1.2 may not either.
This commit is contained in:
@@ -57,7 +57,7 @@ These packages aren't OpenCode plugins. magpie runs them in its gateway, on the
|
||||
| [model-map](packages/model-map) | New API's 模型重定向 (`model_mapping`): send a model under another name, by name or `/pattern/`; replies name the model asked for |
|
||||
| [system-prompt](packages/system-prompt) | Your own system prompt on every request, or on some agents' or models', in each API's own place |
|
||||
| [word-guard](packages/word-guard) | New API's 敏感词过滤: turn away or mask words and patterns in what users send, and in replies |
|
||||
| [think-tags](packages/think-tags) | Take `<think>…</think>` out of a reply's text, or put a Chat reply's `reasoning_content` into it (`thinking_to_content`) |
|
||||
| [think-tags](packages/think-tags) | Take a leading `<think>`, `<thinking>` or `<thought>` block out of a reply's text, or put a Chat reply's `reasoning_content` into it (`thinking_to_content`) |
|
||||
| [antigravity-cloak](packages/antigravity-cloak) | Claude Code and Claude Desktop on Antigravity: break the words Antigravity turns their system prompt away for, in what Antigravity alone is sent |
|
||||
| [codex-history](packages/codex-history) | Opt-in Responses history compatibility after switching providers: remove historical ciphertext and optional item IDs while preserving readable content and tool-call pairing |
|
||||
| [history-trim](packages/history-trim) | Send a request's history smaller: fold a run of blank lines, drop a system prompt written twice and a message repeated right after itself, and cut a past tool result longer than `maxToolLength` at a word boundary |
|
||||
|
||||
@@ -10,10 +10,10 @@ Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @m
|
||||
{ "mode": "strip" }
|
||||
```
|
||||
|
||||
**`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.
|
||||
**`strip`** (the default). Some models (open reasoning models served by vLLM, Ollama and many relays) write their thinking into the reply as `<think>…</think>`, `<thinking>…</thinking>` or `<thought>…</thought>`. 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.
|
||||
- Only a block at the start of the text is taken out, and it ends at its own close tag. A tag the model writes later, in code for example, stays.
|
||||
- A close tag 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.
|
||||
|
||||
@@ -22,4 +22,4 @@ Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @m
|
||||
- This mode works on Chat replies only. An Anthropic thinking block carries a signature, and turned into text it would fail the next turn.
|
||||
- It changes what the agent keeps and sends back, so it suits a chat client better than a coding agent.
|
||||
|
||||
中文:`strip` 去掉回复开头模型写出的 `<think>…</think>`;`to_content` 把 Chat 回复的 reasoning_content 放进正文(New API 的 thinking_to_content)。
|
||||
中文:`strip` 去掉回复开头模型写出的 `<think>…</think>`、`<thinking>…</thinking>` 或 `<thought>…</thought>`;`to_content` 把 Chat 回复的 reasoning_content 放进正文(New API 的 thinking_to_content)。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@magpie-community/middleware-think-tags",
|
||||
"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",
|
||||
"version": "0.1.2",
|
||||
"description": "Take a model's leading <think>, <thinking> or <thought> block 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"],
|
||||
"keywords": ["magpie", "magpie-middleware", "new-api", "reasoning", "think", "llm-gateway"],
|
||||
|
||||
@@ -5,13 +5,16 @@
|
||||
// {"mode": "to_content"}
|
||||
//
|
||||
// "strip": a model that writes its thinking into the reply as
|
||||
// <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. 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.
|
||||
// <think>…</think>, <thinking>…</thinking> or <thought>…</thought> 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. Each block ends at its own
|
||||
// close tag. Only a block that opens the text is taken; a tag later on, in
|
||||
// code the model writes, stays. Within the block, a close tag 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). The three tags are magpie's
|
||||
// thoughtTags (yetone/magpie#5106, plugins#777). 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.
|
||||
@@ -22,6 +25,23 @@
|
||||
const OPEN = "<think>"
|
||||
const CLOSE = "</think>"
|
||||
|
||||
// TAGS are the tags a leading block of thinking comes between, by its
|
||||
// opening tag. No opening tag is a prefix of another's whole tag (<think>
|
||||
// and <thinking> part at the seventh character), so at most one matches.
|
||||
const TAGS = { "<think>": "</think>", "<thinking>": "</thinking>", "<thought>": "</thought>" }
|
||||
|
||||
// opening is the opening tag t starts with, or "" when none does
|
||||
function opening(t) {
|
||||
for (const open in TAGS) if (t.startsWith(open)) return open
|
||||
return ""
|
||||
}
|
||||
|
||||
// mayOpen is whether t, shorter than a whole tag, may be the start of one
|
||||
function mayOpen(t) {
|
||||
for (const open in TAGS) if (t.length < open.length && open.startsWith(t)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
export function onEvent(ev, ctx) {
|
||||
const toContent = ctx.options && ctx.options.mode === "to_content"
|
||||
if (toContent) return Array.isArray(ev.choices) ? reasoningToText(ev, ctx.state) : undefined
|
||||
@@ -115,24 +135,26 @@ function stripItem(it) {
|
||||
return true
|
||||
}
|
||||
|
||||
// stripWhole takes a think block off the start of a whole text: up to its
|
||||
// first </think> outside Markdown code
|
||||
// stripWhole takes a thinking block off the start of a whole text: up to
|
||||
// the first of its own close tag outside Markdown code
|
||||
function stripWhole(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+/, "")
|
||||
const open = opening(t.slice(lead.length))
|
||||
if (!open) return t
|
||||
const close = TAGS[open]
|
||||
const rest = t.slice(lead.length + open.length)
|
||||
const [at] = findClose({ span: 0, fence: 0, mid: false }, rest, true, close)
|
||||
return at < 0 ? t : rest.slice(at + close.length).replace(/^\s+/, "")
|
||||
}
|
||||
|
||||
// findClose gives where </think> is first outside Markdown code in s, read
|
||||
// findClose gives where close 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) {
|
||||
function findClose(m, s, last, close) {
|
||||
for (let j = 0; j < s.length; ) {
|
||||
const c = s[j]
|
||||
if (c === "`") {
|
||||
@@ -155,8 +177,8 @@ function findClose(m, s, last) {
|
||||
} 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]
|
||||
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 {
|
||||
@@ -167,12 +189,13 @@ function findClose(m, s, last) {
|
||||
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 (or, inside, a run of backticks), whether the
|
||||
// text has begun, and where the block is in Markdown code.
|
||||
// strip is a stream's text, a piece at a time, without a thinking block at
|
||||
// its start. Its state, by stream: inside the block (and the close tag it
|
||||
// waits for), text held back that 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, code: { span: 0, fence: 0, mid: false } })
|
||||
const st = state[key] || (state[key] = { inside: false, close: "", carry: "", begun: false, trim: false, code: { span: 0, fence: 0, mid: false } })
|
||||
return (piece) => {
|
||||
if (st.begun) return piece
|
||||
let s = st.carry + piece
|
||||
@@ -180,12 +203,12 @@ function strip(state, key) {
|
||||
let out = ""
|
||||
for (;;) {
|
||||
if (st.inside) {
|
||||
const [i, hold] = findClose(st.code, s, false)
|
||||
const [i, hold] = findClose(st.code, s, false, st.close)
|
||||
if (i < 0) {
|
||||
st.carry = hold ? s.slice(s.length - hold) : ""
|
||||
return out
|
||||
}
|
||||
s = s.slice(i + CLOSE.length)
|
||||
s = s.slice(i + st.close.length)
|
||||
st.inside = false
|
||||
st.trim = true
|
||||
continue
|
||||
@@ -199,13 +222,15 @@ function strip(state, key) {
|
||||
}
|
||||
const lead = /^\s*/.exec(s)[0]
|
||||
const rest = s.slice(lead.length)
|
||||
if (rest.startsWith(OPEN)) {
|
||||
s = rest.slice(OPEN.length)
|
||||
const open = opening(rest)
|
||||
if (open) {
|
||||
s = rest.slice(open.length)
|
||||
st.close = TAGS[open]
|
||||
st.inside = true
|
||||
continue
|
||||
}
|
||||
if (rest.length < OPEN.length && OPEN.startsWith(rest)) {
|
||||
// maybe the start of <think>: wait for the next piece
|
||||
if (mayOpen(rest)) {
|
||||
// maybe the start of an opening tag: wait for the next piece
|
||||
st.carry = s
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -81,3 +81,48 @@ test("a whole reply with a close only in code keeps its text", () => {
|
||||
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")
|
||||
})
|
||||
|
||||
// #777: the three tags magpie's gateway reads a leading block between
|
||||
// (yetone/magpie#5106), each closed by its own end tag, magpie's
|
||||
// TestChatThoughtTags cases for <thinking>
|
||||
const tagged = [
|
||||
["<thinking> whole", ["<thinking>Let me think</thinking>Hi"], "Hi"],
|
||||
["<thinking> split tags", ["<thin", "king>Let me", " think</thin", "king>Hi"], "Hi"],
|
||||
["<thinking> the open tag a chunk alone", ["<thinking>", "Let me think", "</thinking>", "Hi"], "Hi"],
|
||||
["<thinking> a character a delta", chars("<thinking>ab</thinking>\n\ncd"), "cd"],
|
||||
["<thinking> never closed stays thinking", ["<thinking>half", " a thought</thi"], ""],
|
||||
["<thought> whole", ["<thought>Greeting.</thought>Hello"], "Hello"],
|
||||
["<thought> split tags", ["<tho", "ught>Let me", " think</tho", "ught>\n\nHello", " there"], "Hello there"],
|
||||
["<thought> a character a delta", chars("\n<thought>ab</thought>cd"), "cd"],
|
||||
["<think> split where <thinking> could still start", ["<think", ">a</think>b"], "b"],
|
||||
["a <thinking> block ends at </thinking>, not </think>", ["<thinking>a </think> b</thinking>c"], "c"],
|
||||
["a <think> block ends at </think>, not </thinking>", ["<think>a </thinking> b</think>c"], "c"],
|
||||
["a <thought> block ends at </thought>, not </think>", ["<thought>a </think> b</thought>c"], "c"],
|
||||
["a </thinking> in inline code doesn't end the block", ["<thinking>use `</thinking>` here</thinking>\nok"], "ok"],
|
||||
["a <thinking> later on stays", ["Hi <thinking>x</thinking>"], "Hi <thinking>x</thinking>"],
|
||||
["a tag that only looks like one stays", ["<thinkingx>a</thinkingx>b"], "<thinkingx>a</thinkingx>b"],
|
||||
["<thoughts> is not <thought>", chars("<thoughts>a</thoughts>b"), "<thoughts>a</thoughts>b"],
|
||||
]
|
||||
for (const [name, parts, want] of tagged) {
|
||||
test("#777: " + name, () => {
|
||||
expect(streamed(parts)).toBe(want)
|
||||
expect(anthropic(parts)).toBe(want)
|
||||
})
|
||||
}
|
||||
|
||||
test("#777: whole replies with <thinking> and <thought>", () => {
|
||||
const ctx = { protocol: "chat", options: {}, state: {}, status: 200 }
|
||||
for (const [t, want] of [
|
||||
["<thinking>a</thinking>\nb", "b"],
|
||||
["<thought>a</thought>b", "b"],
|
||||
[" <thinking>\na\n</thinking>\n\nb", "b"],
|
||||
["<thinking>a </think> b</thinking>c", "c"],
|
||||
]) {
|
||||
expect(mod.onResponse({ choices: [{ message: { content: t } }] }, ctx).choices[0].message.content).toBe(want)
|
||||
expect(mod.onResponse({ content: [{ type: "text", text: t }] }, ctx).content[0].text).toBe(want)
|
||||
expect(mod.onResponse({ output: [{ type: "message", content: [{ type: "output_text", text: t }] }] }, ctx).output[0].content[0].text).toBe(want)
|
||||
}
|
||||
// never closed: the text stays as it was, as magpie's afterThought leaves it
|
||||
expect(mod.onResponse({ choices: [{ message: { content: "<thinking>never closed" } }] }, ctx)).toBeUndefined()
|
||||
expect(mod.onResponse({ choices: [{ message: { content: "<thinking>a </think> b" } }] }, ctx)).toBeUndefined()
|
||||
})
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@
|
||||
{ "package": "@magpie-community/middleware-word-guard", "name": "Word Guard", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "New API's sensitive-word filter: turn away or mask words and patterns in what you send, and in replies.", "zh": "New API 的敏感词过滤:拒绝或替换你发出的内容和回复里的词与正则。" } },
|
||||
{ "package": "@magpie-community/middleware-think-tags", "name": "Think Tags", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "Take a model's <think>…</think> out of its reply's text, or put a Chat reply's reasoning into it.", "zh": "去掉回复正文开头的 <think>…</think>,或把 Chat 回复的思考内容放进正文。" } },
|
||||
"summary": { "en": "Take a model's leading <think>, <thinking> or <thought> block out of its reply's text, or put a Chat reply's reasoning into it.", "zh": "去掉回复正文开头的 <think>、<thinking> 或 <thought> 思考块,或把 Chat 回复的思考内容放进正文。" } },
|
||||
{ "package": "@magpie-community/agent-kilo", "name": "Kilo Code", "kind": "agent", "community": true, "icon": "https://github.com/Kilo-Org.png",
|
||||
"summary": { "en": "Kilo Code (kilo.ai) on magpie's Agents page: pick one of magpie's models for it, and switch it off to put its config back.", "zh": "把 Kilo Code(kilo.ai)加到 magpie 的 Agent 页:选择 magpie 的模型,关掉即恢复原来的配置。" } },
|
||||
{ "package": "@magpie-community/middleware-antigravity-cloak", "name": "Antigravity Cloak", "kind": "middleware", "community": true,
|
||||
|
||||
Reference in New Issue
Block a user