Skip to content

fix: strip reasoning model thinking tags from document exports - #16687

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
wangq8:bugfix/stripe-think-from-download-doc
Jul 7, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
wangq8:bugfix/stripe-think-from-download-doc

Conversation

@wangq8

@wangq8 wangq8 commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

No description provided.

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)
@wangq8 wangq8 added the ci Continue Integration label Jul 7, 2026
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 7, 2026
@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

A new static helper _strip_thinking removes <think>...</think> blocks and dangling <think> tags from string content, collapsing excess newlines. It is applied in Message._convert_content before format conversion and in DocGenerator._resolve_content before returning generated document content.

Changes

Strip thinking blocks from generated content

Layer / File(s) Summary
Add _strip_thinking helper and wire into message conversion
agent/component/message.py
Adds a static _strip_thinking method that regex-strips think-tag blocks and dangling tags, collapses newlines, and calls it from _convert_content before output-format conversion.
Apply strip_thinking in doc generator content resolution
agent/component/docs_generator.py
_resolve_content now returns self._strip_thinking(content) instead of raw content before downstream PDF/DOCX/TXT/Markdown/HTML generation.

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
Loading

Poem

Think-tags hop away, quick as a hare,
Leaving clean text with nothing to spare.
Docs and messages, tidy and bright,
No more chain-of-thought hiding in sight.
🐇✂️📄 — hop, snip, done!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning No PR description was provided, so the required Summary section is missing. Add a Summary section describing what the PR solves and any background context per the template.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: stripping thinking tags from exported documents.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 318045d and 381c70c.

📒 Files selected for processing (2)
  • agent/component/docs_generator.py
  • agent/component/message.py

Comment on lines +368 to +386
@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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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.

Suggested change
@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

codecov Bot commented Jul 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (318045d) to head (381c70c).
⚠️ Report is 1 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8
wangq8 merged commit 3660b98 into infiniflow:main Jul 7, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants