Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: a literal <think> / </think> in a message is encoded as text (#537)

Niko1221c16f31f85034
diff --git a/serve/frontend.py b/serve/frontend.py
index 007d06df2..02a1d2f9b 100644
--- a/serve/frontend.py
+++ b/serve/frontend.py
@@ -16,6 +16,7 @@ and the formats change often; the engine boundary is token ids in, text deltas o
from __future__ import annotations
import json
+import re
import uuid
from dataclasses import dataclass, field
from pathlib import Path
@@ -135,6 +136,81 @@ def images_of(messages: list[dict]) -> list[str]:
for item in m["content"] if item.get("type") == "image"]
+# #537: a literal <think> / </think> inside a message's text is plain text, not the model's reasoning markers. The
+# tokenizer matches those two strings as their special tokens everywhere (GGUF token type 4, as llama.cpp does), so
+# a user quoting "</think>" used to hand the model a real end-of-reasoning token. Before the template is rendered
+# they are swapped for these private-use characters, and the server encodes the spans they mark as ordinary text.
+THINK_TAGS = {"<think>": "\U000F0E01", "</think>": "\U000F0E02"}
+THINK_MARKS = {v: k for k, v in THINK_TAGS.items()}
+
+
+def _mark(text: str) -> str:
+ for tag, mark in THINK_TAGS.items():
+ text = text.replace(tag, mark)
+ return text
+
+
+def _mark_deep(v):
+ if isinstance(v, str):
+ return _mark(v)
+ if isinstance(v, dict):
+ return {k: _mark_deep(x) for k, x in v.items()}
+ if isinstance(v, list):
+ return [_mark_deep(x) for x in v]
+ return v
+
+
+def _has_tag(v) -> bool:
+ if isinstance(v, str):
+ return "<think>" in v or "</think>" in v
+ if isinstance(v, dict):
+ return any(_has_tag(x) for x in v.values())
+ if isinstance(v, list):
+ return any(_has_tag(x) for x in v)
+ return False
+
+
+def mark_think_literals(messages: list[dict], tools: list[dict] | None):
+ """#537: (messages, tools) with every literal <think> / </think> in their text swapped for THINK_TAGS' marks, and
+ whether there was one (None: no change, the same objects back - a prompt without them renders as it always did).
+ An assistant message whose content opens with a whole <think>...</think> block (clients that send the reasoning
+ inline) keeps that one block as the model's markers, as before."""
+ if not _has_tag(messages) and not _has_tag(tools):
+ return messages, tools, False
+ out = []
+ for m in messages:
+ m = dict(m)
+ content = m.get("content")
+ for k, v in m.items():
+ if k != "role":
+ m[k] = _mark_deep(v)
+ if m.get("role") == "assistant" and isinstance(content, str) and content.lstrip().startswith("<think>") \
+ and "</think>" in content:
+ i, j = content.index("<think>") + len("<think>"), content.index("</think>")
+ m["content"] = content[:i] + _mark(content[i:j]) + "</think>" + _mark(content[j + len("</think>"):])
+ out.append(m)
+ return out, _mark_deep(tools), True
+
+
+_THINK_MARK_RE = re.compile("|".join(THINK_MARKS))
+
+
+def unmark_think_literals(prompt: str) -> tuple[str, list[tuple[int, int]]]:
+ """The rendered prompt with THINK_TAGS' marks turned back into the tags' text, and the (start, end) spans of those
+ tags in it: the server encodes them as ordinary text (the tokenizer's encode_plain_spans)."""
+ out, spans, pos, n = [], [], 0, 0
+ for m in _THINK_MARK_RE.finditer(prompt):
+ out.append(prompt[pos:m.start()])
+ n += m.start() - pos
+ tag = THINK_MARKS[m.group(0)]
+ out.append(tag)
+ spans.append((n, n + len(tag)))
+ n += len(tag)
+ pos = m.end()
+ out.append(prompt[pos:])
+ return "".join(out), spans
+
+
def _late_system_to_user(messages: list[dict]) -> list[dict]:
"""The chat template takes a system message only at the start ("System message must be at the beginning").
Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user
diff --git a/serve/server.py b/serve/server.py
index 5deeb9d0d..9ed8d7beb 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -51,7 +51,7 @@ ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools"))
sys.path.insert(0, str(ROOT)) # run as a script (run-<model>.bat) as well as a module
from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402
- images_of, openai_to_messages)
+ images_of, mark_think_literals, openai_to_messages, unmark_think_literals)
from serve.mcp import McpCancelled, hub_from_config # noqa: E402
from serve.winjob import contain # noqa: E402
from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402
@@ -893,11 +893,14 @@ class ByteTokenizer:
"""Tiny stand-in tokenizer for tests without the pack: one id per UTF-8 byte, specials as ids >= 256."""
SPECIALS = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<|vision_end|>"]
- def encode(self, text, parse_special=False):
+ ALWAYS = () # specials matched without parse_special (type 4, as <think>)
+
+ def encode(self, text, parse_special=False, plain=()):
out, i = [], 0
while i < len(text):
for k, s in enumerate(self.SPECIALS):
- if parse_special and text.startswith(s, i):
+ if (parse_special or s in self.ALWAYS) and text.startswith(s, i) and not any(
+ a <= i < b for a, b in plain):
out.append(256 + k)
i += len(s)
break
@@ -1334,11 +1337,20 @@ class Service:
"ram": {"used_gib": scaled(hw.get("ram_used"), 2 ** 30, 1),
"total_gib": scaled(hw.get("ram_total"), 2 ** 30, 1)} if hw.get("ram_total") else None}}
+ def encode_prompt(self, messages, tools, kwargs) -> list[int]:
+ """The request's prompt: the template rendered and tokenized. #537: a <think> / </think> written inside a
+ message's text is encoded as the text it is, not as the model's reasoning markers (the template's own are)."""
+ marked, marked_tools, changed = mark_think_literals(messages, tools)
+ prompt = self.template.render(marked, tools=marked_tools, **kwargs)
+ if not changed:
+ return self.tok.encode(prompt, parse_special=True)
+ prompt, plain = unmark_think_literals(prompt)
+ return self.tok.encode(prompt, parse_special=True, plain=plain)
+
def prepare(self, messages, tools, kwargs, max_new=None):
"""-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited":
the rest of the context."""
- prompt = self.template.render(messages, tools=tools, **kwargs)
- ids = self.tok.encode(prompt, parse_special=True)
+ ids = self.encode_prompt(messages, tools, kwargs)
self.embeddings.path = None
images = images_of(messages)
if images:
@@ -2471,8 +2483,7 @@ def make_handler(svc: Service):
read for the same request, rendered and tokenized - the model does not run."""
req = svc.with_shared(req, "anthropic")
messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked)
- prompt = svc.template.render(messages, tools=tools, **kw)
- self._json(200, {"input_tokens": len(svc.tok.encode(prompt, parse_special=True))})
+ self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw))})
def _anthropic(self, req):
svc.load()
diff --git a/serve/test_server.py b/serve/test_server.py
index 51101e695..cb96d1f9d 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -241,6 +241,84 @@ class ImageMarkers(unittest.TestCase):
svc.embeddings.path.unlink(missing_ok=True)
+class ThinkTokenizer(ByteTokenizer):
+ """The byte tokenizer with the model's reasoning markers as specials that are matched even without parse_special,
+ as the real tokenizer does (GGUF token type 4)."""
+ SPECIALS = ByteTokenizer.SPECIALS + ["<think>", "</think>"]
+ ALWAYS = ("<think>", "</think>")
+
+
+class LiteralThinkTags(unittest.TestCase):
+ """#537: a <think> / </think> written inside a message is text, not the model's reasoning markers: a quoted
+ "</think>" no longer ends the model's reasoning before it starts. The template's own markers stay special."""
+
+ @classmethod
+ def setUpClass(cls):
+ cls.tok = ThinkTokenizer()
+ cls.svc = Service(MockEngine(cls.tok, "ok", max_context=CTX), cls.tok,
+ ChatTemplate(ROOT / "serve/chat_template.jinja"))
+ cls.open, cls.close = (cls.tok.encode(t)[0] for t in ("<think>", "</think>"))
+
+ def ids(self, messages, tools=None, **kw):
+ return self.svc.prepare(messages, tools, kw)[0]
+
+ def old_ids(self, messages, tools=None, **kw):
+ return self.tok.encode(self.svc.template.render(messages, tools=tools, **kw), parse_special=True)
+
+ def test_a_quoted_tag_in_a_user_message(self):
+ text = "Quote this exact literal string, then explain it: </think> and <think>"
+ ids = self.ids([{"role": "user", "content": text}])
+ self.assertEqual(ids.count(self.close), 0)
+ self.assertEqual(ids.count(self.open), 1) # the generation prompt's own
+ self.assertEqual(ids[-2:], [self.open, ord("\n")])
+ self.assertIn(text, self.tok.decode(ids)) # the text is all there, as text
+ self.assertEqual(ids.count(self.close), 0)
+ # thinking off: the template's empty block stays two specials, the user's tag is text
+ ids = self.ids([{"role": "user", "content": text}], enable_thinking=False)
+ self.assertEqual((ids.count(self.open), ids.count(self.close)), (1, 1))
+
+ def test_without_a_tag_the_prompt_is_unchanged(self):
+ msgs = [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "1+1?"},
+ {"role": "assistant", "content": "2", "reasoning_content": "easy"}, {"role": "user", "content": "x"}]
+ self.assertEqual(self.ids(msgs), self.old_ids(msgs))
+ self.assertEqual(self.ids(msgs, enable_thinking=False), self.old_ids(msgs, enable_thinking=False))
+
+ def test_history_tool_results_and_tools(self):
+ msgs = [{"role": "user", "content": "go"},
+ {"role": "assistant", "content": "It wrote </think> here.", "reasoning_content": "the </think> tag",
+ "tool_calls": [{"function": {"name": "write", "arguments": {"text": "a </think> b"}}}]},
+ {"role": "tool", "content": "file has <think> in it"},
+ {"role": "user", "content": "why did you write </think>"}]
+ tools = [{"name": "write", "description": "writes text (may contain </think>)", "parameters": {}}]
+ ids = self.ids(msgs, tools)
+ # the template's markers: the history turn's <think>...</think> and the generation prompt's <think>
+ self.assertEqual((ids.count(self.open), ids.count(self.close)), (2, 1))
+ text = self.tok.decode(ids)
+ for part in ("It wrote </think> here.", "the </think> tag", "a </think> b", "file has <think> in it",
+ "why did you write </think>", "may contain </think>"):
+ self.assertIn(part, text)
+
+ def test_a_client_that_sends_the_reasoning_inline(self):
+ # an assistant turn whose content opens with its own <think>...</think> block keeps that block's markers
+ msgs = [{"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "<think>\nplan: say </x> hello\n</think>\n\nHello, </think> is a tag."},
+ {"role": "user", "content": "again"}]
+ ids = self.ids(msgs)
+ self.assertEqual((ids.count(self.open), ids.count(self.close)), (3, 2)) # template's + the inline block's
+ self.assertIn("Hello, </think> is a tag.", self.tok.decode(ids))
+
+ def test_the_real_tokenizer_reads_the_tag_as_text(self):
+ import strata_tokenizer as ST
+ b2u = ST.bytes_to_unicode()
+ tokens = [b2u[b] for b in range(256)] + ["<think>", "</think>", "<|im_end|>"]
+ tok = ST.Tokenizer(tokens, [], [1] * 256 + [4, 4, 3])
+ text = "say </think> now<|im_end|>"
+ self.assertEqual(tok.encode(text, parse_special=True), [*b"say ", 257, *b" now", 258])
+ start = text.index("</think>")
+ plain = tok.encode(text, parse_special=True, plain=[(start, start + len("</think>"))])
+ self.assertEqual(plain, [*b"say </think> now", 258]) # the tag as text, im_end still special
+
+
class StatusNeedsTheKey(unittest.TestCase):
"""#212: /status shows the end of the answer being written, so it needs the key like /v1/*."""
diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py
index c14492cb9..8b794191e 100644
--- a/tools/strata_tokenizer.py
+++ b/tools/strata_tokenizer.py
@@ -213,18 +213,21 @@ class Tokenizer:
out.append(i)
return out
- def _encode_matching(self, text: str, pat) -> list[int]:
+ def _encode_matching(self, text: str, pat, plain=()) -> list[int]:
"""Encode `text`, emitting any literal `pat` matches as single tokens and BPE-ing the rest.
The split happens on the RAW text, before the byte mapping, because a special token's string is a
literal to match rather than bytes to decompose. Everything between the matches is tokenized
- normally - which is why a near-miss like `<|im_star` still costs ordinary tokens.
+ normally - which is why a near-miss like `<|im_star` still costs ordinary tokens. A match that starts
+ inside one of the `plain` (start, end) spans is left to the text around it (#537).
"""
if pat is None:
return self._encode_plain(text)
out: list[int] = []
pos = 0
for m in pat.finditer(text):
+ if plain and any(a <= m.start() < b for a, b in plain):
+ continue
if m.start() > pos:
out.extend(self._encode_plain(text[pos:m.start()]))
out.append(self.special_tokens[m.group(0)])
@@ -233,13 +236,15 @@ class Tokenizer:
out.extend(self._encode_plain(text[pos:]))
return out
- def encode(self, text: str, parse_special: bool = False) -> list[int]:
+ def encode(self, text: str, parse_special: bool = False, plain=()) -> list[int]:
"""Tokenize `text`.
`parse_special` controls only the type-3 CONTROL literals such as `<|im_end|>`; the type-4
USER_DEFINED ones such as `<think>` are matched either way. See the note in `__init__`.
+ `plain`: (start, end) spans of `text` that are ordinary text even where they spell a literal - a
+ `</think>` quoted in a message (#537) - and are tokenized with the text around them.
"""
- return self._encode_matching(text, self._special_re if parse_special else self._always_re)
+ return self._encode_matching(text, self._special_re if parse_special else self._always_re, plain)
def token_bytes(self, i: int) -> bytes:
"""The raw bytes of one token (a multi-byte character can be split across tokens)."""