diff --git a/deeptutor/services/llm/utils.py b/deeptutor/services/llm/utils.py index 74712f37f..971b84e59 100644 --- a/deeptutor/services/llm/utils.py +++ b/deeptutor/services/llm/utils.py @@ -187,19 +187,56 @@ def clean_thinking_tags( if not content: return "" - closed_pattern = re.compile( - r"`?<\s*(?Pthink(?: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"(?]*>`.*?`<\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() diff --git a/tests/services/llm/test_utils.py b/tests/services/llm/test_utils.py index 4c15ee48f..6ccb477e9 100644 --- a/tests/services/llm/test_utils.py +++ b/tests/services/llm/test_utils.py @@ -82,6 +82,32 @@ def test_clean_thinking_tags_handles_backtick_wrapped_tags() -> None: assert clean_thinking_tags("``ignore``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 to start a reasoning block.") + == "Use to start a reasoning block." + ) + assert ( + clean_thinking_tags("The `` tag marks the scratchpad.") + == "The `` tag marks the scratchpad." + ) + + +def test_clean_thinking_tags_closes_on_either_spelling() -> None: + """... is a closed block, not an unterminated one.""" + assert clean_thinking_tags("reasoninganswer") == "answer" + assert clean_thinking_tags("reasoninganswer") == "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("rThe tag is a marker.") + == "The 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\n```\nThis is literal code.", + "Example:\n~~~xml\nprivate\n~~~\nKeep this answer.", + "Use `secret` to illustrate the format.", + "```` is an inline marker.", + "```xml\n\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("secret\n```python\nprivate()\n```\nAnswer") + == "Answer" + ) + assert ( + clean_thinking_tags("```xml\n\n```\nsecretAnswer") + == "```xml\n\n```\nAnswer" + )