Merge PR #2562: fix(llm): stop dropping the answer when a reply mentions <think>

Protect fenced and inline Markdown examples while stripping real closed, mixed-spelling, and interrupted reasoning blocks; add regressions for literal tags and code inside reasoning.
This commit is contained in:
Bingxi Zhao (Frank)
2026-11-14 23:08:02 +08:00
2 changed files with 97 additions and 9 deletions

View File

@@ -187,19 +187,56 @@ def clean_thinking_tags(
if not content:
return ""
closed_pattern = re.compile(
r"`?<\s*(?P<tag>think(?:ing)?)\b[^>]*>`?.*?`?<\s*/\s*(?P=tag)\s*>`?",
# Mask Markdown code before recognizing protocol tags. Keep offsets intact
# so stripping a real reasoning block can still discard its entire body,
# including any code inside that block, without rewriting literal examples.
masked = list(content)
fenced: list[tuple[int, int]] = []
cursor = 0
opening_fence = re.compile(r"(?m)^[ \t]{0,3}(`{3,}|~{3,})[^\n]*\n")
while opening := opening_fence.search(content, cursor):
marker = opening[1]
closing = re.compile(
rf"(?m)^[ \t]{{0,3}}{re.escape(marker[0])}{{{len(marker)},}}[ \t]*(?:\n|$)"
).search(content, opening.end())
end = closing.end() if closing else len(content)
fenced.append((opening.start(), end))
cursor = end
inline = re.compile(r"(?<!`)(`+)(?!`).*?(?<!`)\1(?!`)", re.DOTALL)
wrapped = re.match(
r"\s*`<\s*think(?:ing)?\b[^>]*>`.*?`<\s*/\s*think(?:ing)?\s*>`",
content,
re.DOTALL | re.IGNORECASE,
)
cleaned = re.sub(closed_pattern, "", content)
# Streaming providers can surface a final partial block if the request is
# interrupted after reasoning has started. Never expose that scratchpad.
unclosed_pattern = re.compile(
r"`?<\s*think(?:ing)?\b[^>]*>`?.*$",
ranges = list(fenced)
for match in inline.finditer(content):
if any(a <= match.start() < b for a, b in fenced):
continue
# Some adapters wrap individual protocol markers in backticks. Retain
# that legacy leading-block form, while protecting whole inline examples.
if (
wrapped
and match.end() <= wrapped.end()
and re.fullmatch(r"`<\s*/?\s*think(?:ing)?\b[^>]*>`", match[0], re.IGNORECASE)
):
continue
ranges.append(match.span())
for start, end in ranges:
masked[start:end] = ["\n" if char == "\n" else " " for char in content[start:end]]
# Either spelling closes a real block. An unclosed scratchpad must begin
# a line; mentioning an opening marker in ordinary prose is not reasoning.
tags = re.compile(
r"`?<\s*think(?:ing)?\b[^>]*>`?.*?`?<\s*/\s*think(?:ing)?\s*>`?"
r"|(?:\A|\n)[ \t]*`?<\s*think(?:ing)?\b[^>]*>`?"
r"(?!.*?<\s*/\s*think(?:ing)?\s*>).*\Z"
r"|`?<\s*/\s*think(?:ing)?\s*>`?",
re.DOTALL | re.IGNORECASE,
)
cleaned = re.sub(unclosed_pattern, "", cleaned)
cleaned = re.sub(r"`?<\s*/\s*think(?:ing)?\s*>`?", "", cleaned, flags=re.IGNORECASE)
cleaned = content
for match in reversed(list(tags.finditer("".join(masked)))):
cleaned = cleaned[: match.start()] + cleaned[match.end() :]
return cleaned.strip()

View File

@@ -82,6 +82,32 @@ def test_clean_thinking_tags_handles_backtick_wrapped_tags() -> None:
assert clean_thinking_tags("`<think>`ignore`</think>`Hello") == "Hello"
def test_clean_thinking_tags_keeps_prose_that_names_the_tag() -> None:
"""A reply explaining the tag is prose, not an unterminated scratchpad."""
assert (
clean_thinking_tags("Use <think> to start a reasoning block.")
== "Use <think> to start a reasoning block."
)
assert (
clean_thinking_tags("The `<think>` tag marks the scratchpad.")
== "The `<think>` tag marks the scratchpad."
)
def test_clean_thinking_tags_closes_on_either_spelling() -> None:
"""<think>...</thinking> is a closed block, not an unterminated one."""
assert clean_thinking_tags("<think>reasoning</thinking>answer") == "answer"
assert clean_thinking_tags("<thinking>reasoning</think>answer") == "answer"
def test_clean_thinking_tags_keeps_text_after_a_closed_block() -> None:
"""Only the block is removed; a later literal mention survives intact."""
assert (
clean_thinking_tags("<think>r</think>The <think> tag is a marker.")
== "The <think> tag is a marker."
)
def test_extract_response_content() -> None:
"""Response content extraction should handle mapping payloads."""
payload = {"content": [{"text": "Hello"}, {"text": "World"}]}
@@ -127,3 +153,28 @@ def test_build_auth_headers() -> None:
assert build_auth_headers("key", binding="anthropic")["x-api-key"] == "key"
assert build_auth_headers("key", binding="azure")["api-key"] == "key"
assert build_auth_headers("key")["Authorization"] == "Bearer key"
@pytest.mark.parametrize(
"literal",
[
"Example:\n```xml\n<think>\n```\nThis is literal code.",
"Example:\n~~~xml\n<think>private</thinking>\n~~~\nKeep this answer.",
"Use `<think>secret</think>` to illustrate the format.",
"``<think>`` is an inline marker.",
"```xml\n<think>\n````\nAfter the longer closing fence.",
],
)
def test_clean_thinking_tags_preserves_literal_code(literal: str) -> None:
assert clean_thinking_tags(literal) == literal
def test_clean_thinking_tags_discards_code_inside_real_reasoning() -> None:
assert (
clean_thinking_tags("<think>secret\n```python\nprivate()\n```\n</thinking>Answer")
== "Answer"
)
assert (
clean_thinking_tags("```xml\n<think>\n```\n<think>secret</think>Answer")
== "```xml\n<think>\n```\nAnswer"
)