Repository navigation
fix: strip reasoning model thinking tags from document exports - #16687
Conversation
Reasoning models (e.g. DeepSeek-R1, OpenAI o1) wrap chain-of-thought inside <think>...</think> tags. These blocks were leaking into exported Word/PDF/ Excel/TXT/Markdown/HTML documents generated by the Message and DocGenerator agent components. - Add Message._strip_thinking() to remove <think> blocks (handles complete blocks, unclosed tags, leftover standalone tags, and collapses excess blank lines left behind) - Call it at the start of Message._convert_content (covers all Message export formats: markdown, html, pdf, docx, xlsx) - Call it before returning from DocGenerator._resolve_content (inherits the method from Message; covers pdf, docx, txt, markdown, html)
📝 WalkthroughWalkthroughA new static helper ChangesStrip thinking blocks from generated content
Estimated code review effort: 1 (Trivial) | ~5 minutes Sequence Diagram(s)sequenceDiagram
participant Caller
participant Message
participant Pypandoc
Caller->>Message: _convert_content(content)
Message->>Message: _strip_thinking(content)
Message->>Pypandoc: convert cleaned content
Pypandoc-->>Caller: converted output
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@agent/component/message.py`:
- Around line 368-386: The _strip_thinking helper currently sanitizes <think>
content without any traceability, so add logging in Message._strip_thinking to
record when the new stripping flow actually removes reasoning blocks or dangling
tags. Instrument the content cleanup steps to log useful summary details such as
whether complete blocks were removed, whether an unclosed opening tag was found,
and how many tags/blocks were stripped, while keeping the returned cleaned text
unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2648590e-09b0-4a78-b2f6-a4f989fc9a38
📒 Files selected for processing (2)
agent/component/docs_generator.pyagent/component/message.py
| @staticmethod | ||
| def _strip_thinking(content: str) -> str: | ||
| """Remove <think>...</think> reasoning blocks before document export. | ||
|
|
||
| Reasoning models (e.g. DeepSeek-R1, OpenAI o1) embed chain-of-thought | ||
| inside ``<think>`` tags. These blocks must not leak into exported | ||
| Word/PDF/Excel documents. | ||
| """ | ||
| if not isinstance(content, str) or not content: | ||
| return content | ||
| # Remove complete think blocks (DOTALL so newlines are matched) | ||
| cleaned = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL) | ||
| # Remove any dangling unclosed <think> opening tag + trailing content | ||
| cleaned = re.sub(r"<think>.*$", "", cleaned, flags=re.DOTALL) | ||
| # Remove leftover standalone tags | ||
| cleaned = re.sub(r"</?think>", "", cleaned) | ||
| # Collapse 3+ consecutive newlines left behind by removed blocks | ||
| cleaned = re.sub(r"\n{3,}", "\n\n", cleaned) | ||
| return cleaned.strip() |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Add logging for this new strip-thinking flow.
The helper implements a new content-sanitization flow but never logs when it actually strips content (e.g., how many <think> blocks were removed, or that a dangling tag was found), making it hard to trace whether reasoning leakage is actually being caught in exported documents. As per coding guidelines, "Add logging for new flows".
📝 Suggested logging addition
`@staticmethod`
def _strip_thinking(content: str) -> str:
"""Remove <think>...</think> reasoning blocks before document export.
Reasoning models (e.g. DeepSeek-R1, OpenAI o1) embed chain-of-thought
inside ``<think>`` tags. These blocks must not leak into exported
Word/PDF/Excel documents.
"""
if not isinstance(content, str) or not content:
return content
# Remove complete think blocks (DOTALL so newlines are matched)
cleaned = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL)
# Remove any dangling unclosed <think> opening tag + trailing content
cleaned = re.sub(r"<think>.*$", "", cleaned, flags=re.DOTALL)
# Remove leftover standalone tags
cleaned = re.sub(r"</?think>", "", cleaned)
# Collapse 3+ consecutive newlines left behind by removed blocks
cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
- return cleaned.strip()
+ result = cleaned.strip()
+ if len(result) != len(content.strip()):
+ logging.info("Stripped thinking block(s) from content before export (%s -> %s chars)", len(content), len(result))
+ return result📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| @staticmethod | |
| def _strip_thinking(content: str) -> str: | |
| """Remove <think>...</think> reasoning blocks before document export. | |
| Reasoning models (e.g. DeepSeek-R1, OpenAI o1) embed chain-of-thought | |
| inside ``<think>`` tags. These blocks must not leak into exported | |
| Word/PDF/Excel documents. | |
| """ | |
| if not isinstance(content, str) or not content: | |
| return content | |
| # Remove complete think blocks (DOTALL so newlines are matched) | |
| cleaned = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL) | |
| # Remove any dangling unclosed <think> opening tag + trailing content | |
| cleaned = re.sub(r"<think>.*$", "", cleaned, flags=re.DOTALL) | |
| # Remove leftover standalone tags | |
| cleaned = re.sub(r"</?think>", "", cleaned) | |
| # Collapse 3+ consecutive newlines left behind by removed blocks | |
| cleaned = re.sub(r"\n{3,}", "\n\n", cleaned) | |
| return cleaned.strip() | |
| `@staticmethod` | |
| def _strip_thinking(content: str) -> str: | |
| """Remove <think>...</think> reasoning blocks before document export. | |
| Reasoning models (e.g. DeepSeek-R1, OpenAI o1) embed chain-of-thought | |
| inside ``<think>`` tags. These blocks must not leak into exported | |
| Word/PDF/Excel documents. | |
| """ | |
| if not isinstance(content, str) or not content: | |
| return content | |
| # Remove complete think blocks (DOTALL so newlines are matched) | |
| cleaned = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL) | |
| # Remove any dangling unclosed <think> opening tag + trailing content | |
| cleaned = re.sub(r"<think>.*$", "", cleaned, flags=re.DOTALL) | |
| # Remove leftover standalone tags | |
| cleaned = re.sub(r"</?think>", "", cleaned) | |
| # Collapse 3+ consecutive newlines left behind by removed blocks | |
| cleaned = re.sub(r"\n{3,}", "\n\n", cleaned) | |
| result = cleaned.strip() | |
| if len(result) != len(content.strip()): | |
| logging.info("Stripped thinking block(s) from content before export (%s -> %s chars)", len(content), len(result)) | |
| return result |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@agent/component/message.py` around lines 368 - 386, The _strip_thinking
helper currently sanitizes <think> content without any traceability, so add
logging in Message._strip_thinking to record when the new stripping flow
actually removes reasoning blocks or dangling tags. Instrument the content
cleanup steps to log useful summary details such as whether complete blocks were
removed, whether an unclosed opening tag was found, and how many tags/blocks
were stripped, while keeping the returned cleaned text unchanged.
Source: Coding guidelines
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16687 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
No description provided.