Skip to content

feat(agent): expose thinking mode control per LLM node in Agent canvas - #16640

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
AI-Mart:feat/agent-node-thinking-mode
Jul 6, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
AI-Mart:feat/agent-node-thinking-mode

Conversation

@AI-Mart

@AI-Mart AI-Mart commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Summary

Add per-node thinking mode control for LLM components in RAGFlow Agent canvas, supporting Qwen3/Qwen3.6/B200M thinking-capable models. Users can now independently configure thinking mode (thinking/non-thinking) for each LLM node via the existing UI dropdown.

Motivation

When Qwen3.6-27B (and other thinking-capable models like Qwen3-32B, B200M) are used in RAGFlow Agent nodes, different nodes need different thinking behavior:

  • Reasoning nodes (complex analysis, math, coding): thinking mode ON
  • Simple nodes (direct Q&A, intent classification): thinking mode OFF

The web UI already has a thinking dropdown (default/enabled/disabled) in LLM settings, and the LLM backend _apply_model_family_policies() already supports enable_thinking. The missing link was gen_conf() not forwarding the parameter.

This 3-line fix completes the chain.

Changes

agent/component/llm.py — LLMParam.gen_conf():

if hasattr(self, "thinking") and self.thinking and self.thinking != "default":
    conf["thinking"] = self.thinking

End-to-end flow

UI dropdown: default / enabled / disabled
  → DSL: {"thinking": "enabled"}
    → LLMParam.thinking = "enabled"
      → gen_conf() returns {"thinking": "enabled"}
        → _apply_model_family_policies()
          → extra_body {enable_thinking: true}
            → Model API call with thinking ON

Backward compatibility

  • Fully backward compatible — only 3 lines added, nothing changed
  • When thinking is "default" or not set, existing behavior is preserved
  • Qwen3 models default to enable_thinking: false (non-thinking), unchanged

Related issues

Testing

  • Verified in test/unit_test/rag/llm/test_chat_model_thinking_policy.py that thinking policy already tested for Qwen3 models
  • The 3-line change passes through existing tested code path (_apply_model_family_policies)

When Qwen3/Qwen3.6/B200M (and other thinking-capable models) are used
in RAGFlow Agent nodes, there is currently no way to control whether
the model should reason (thinking mode) or answer directly (non-thinking
mode) on a per-node basis.

The web UI already has a `thinking` dropdown (default/enabled/disabled)
for LLM settings, and the LLM backend already supports `enable_thinking`
via `_apply_model_family_policies()`. However, the LLM component
parameter `gen_conf()` method never passes the `thinking` field through.

This commit bridges the gap by forwarding the `thinking` parameter
from the LLMParam to gen_conf(), completing the chain:

  UI (default/enabled/disabled)
    → DSL config
      → LLMParam.thinking
        → gen_conf() {"thinking": "..."}
          → _apply_model_family_policies()
            → extra_body {enable_thinking: true/false}
              → model API call

No breaking changes. When thinking is "default" or not set, existing
behaviour is preserved (Qwen3 defaults to non-thinking).
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 5, 2026
@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

LLMParam.gen_conf() in agent/component/llm.py is modified to include a "thinking" key in the generated configuration dictionary whenever the instance's thinking attribute is set to a truthy value other than "default".

Changes

Thinking Configuration Support

Layer / File(s) Summary
Conditional thinking field in gen_conf
agent/component/llm.py
gen_conf() adds conf["thinking"] to the returned configuration when self.thinking is truthy and not "default".

Estimated code review effort: 1 (Trivial) | ~2 minutes

Possibly related issues

Possibly related PRs

  • infiniflow/ragflow#15446: Both PRs modify LLMParam/gen_conf() in agent/component/llm.py to conditionally emit a "thinking" configuration.

Poem

A hop, a thought, a tiny switch,
"thinking" now joins the config stitch.
No more guessing, mode so clear,
"default" stays quiet, others appear.
🐇 Thump thump — reasoning's here!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main change: per-node thinking control for LLM components in the Agent canvas.
Description check ✅ Passed The description includes the required summary and adds relevant context, changes, compatibility, and testing details.
Linked Issues check ✅ Passed The change forwards the thinking setting into LLM config, matching the linked issues' need to control reasoning visibility in agent API behavior.
Out of Scope Changes check ✅ Passed The diff is narrowly scoped to the thinking config pass-through and introduces no unrelated changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
agent/component/llm.py (1)

39-51: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Initialize self.thinking in __init__ instead of using hasattr.

Every other core value param (max_tokens, temperature, top_p, presence_penalty, frequency_penalty) is initialized in __init__ and read unconditionally. thinking is the same category of attribute, yet it's read defensively via hasattr at Line 80. This is inconsistent with the class's own pattern (the hasattr/get_attr defensive style is otherwise reserved for the *Enabled feature-flag attributes at lines 64-68, not core values), and leaves self.thinking undefined by default, which risks silent no-ops if some other part of the codebase (e.g. serialization, checks) accesses self.thinking directly without a guard.

♻️ Proposed fix
     def __init__(self):
         super().__init__()
         self.llm_id = ""
         self.sys_prompt = ""
         self.prompts = [{"role": "user", "content": "{sys.query}"}]
         self.max_tokens = 0
         self.temperature = 0
         self.top_p = 0
         self.presence_penalty = 0
         self.frequency_penalty = 0
         self.output_structure = None
         self.cite = True
         self.visual_files_var = None
+        self.thinking = "default"
-        if hasattr(self, "thinking") and self.thinking and self.thinking != "default":
+        if self.thinking and self.thinking != "default":
             conf["thinking"] = self.thinking

Also applies to: 80-81

🤖 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/llm.py` around lines 39 - 51, Initialize the core `thinking`
field in `LLM.__init__` alongside `max_tokens`, `temperature`, and the other
scalar defaults so it always exists on the instance. Then update the `LLM` logic
that currently uses `hasattr` around `self.thinking` to read it directly like
the other core params, keeping `get_attr`/`hasattr` only for the `*Enabled`
feature-flag attributes.
🤖 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/llm.py`:
- Around line 80-81: Map the agent-level thinking setting to the adapter’s
expected contract before building conf in the LLM component. In the logic around
the self.thinking check, normalize/translate the field so downstream adapters
receive the shape they expect (for example, align it with the reasoning handling
used in rag/llm/chat_model.py rather than forwarding thinking verbatim). Update
the configuration assembly in the relevant llm model class so bundle calls
always get the adapter-compatible key/value.

---

Outside diff comments:
In `@agent/component/llm.py`:
- Around line 39-51: Initialize the core `thinking` field in `LLM.__init__`
alongside `max_tokens`, `temperature`, and the other scalar defaults so it
always exists on the instance. Then update the `LLM` logic that currently uses
`hasattr` around `self.thinking` to read it directly like the other core params,
keeping `get_attr`/`hasattr` only for the `*Enabled` feature-flag attributes.
🪄 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: b8ffed03-8601-4f08-9e03-126b4b3b320b

📥 Commits

Reviewing files that changed from the base of the PR and between 0fcfb38 and d7e21d5.

📒 Files selected for processing (1)
  • agent/component/llm.py

Comment thread agent/component/llm.py
Comment on lines +80 to +81
if hasattr(self, "thinking") and self.thinking and self.thinking != "default":
conf["thinking"] = self.thinking

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Locate and inspect _apply_model_family_policies to confirm it normalizes the "thinking" string value
rg -n "_apply_model_family_policies" -A 30 --type=py

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- agent/component/llm.py ---'
if [ -f agent/component/llm.py ]; then
  wc -l agent/component/llm.py
  sed -n '1,180p' agent/component/llm.py
fi

echo '--- search for thinking handling ---'
rg -n "thinking|model_family|kimi-k2\.5|k2\.5|apply_model_family_policies|completion handler" agent rag api -S

echo '--- candidate python files ---'
fd -a 'llm.py' agent rag api || true
fd -a 'chat_model.py' agent rag api || true

Repository: infiniflow/ragflow

Length of output: 12560


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- rag/llm/chat_model.py (policy section) ---'
sed -n '60,120p' rag/llm/chat_model.py

echo '--- call sites that pass gen_conf / kwargs into model policy ---'
rg -n "apply_model_family_policies|gen_conf|thinking" rag/llm/chat_model.py agent/component/llm.py api/db/services/llm_service.py -n -A 8 -B 4

echo '--- LLMBundle definition ---'
sed -n '1,260p' api/db/services/llm_service.py

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- search for self.thinking assignment / UI contract ---'
rg -n "\bthinking\b" agent api rag web frontend ui -S

echo '--- inspect llm component around parameter declaration / form generation ---'
sed -n '1,140p' agent/component/llm.py

echo '--- inspect any serialization or defaults for thinking ---'
rg -n "thinking.*default|default.*thinking|enabled|disabled" agent api rag web webui frontend -S

Repository: infiniflow/ragflow

Length of output: 4769


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- agent/component/llm.py around param object and any thinking defaults ---'
sed -n '1,120p' agent/component/llm.py

echo '--- search for thinking parameter definitions in agent/web ---'
rg -n '"thinking"|thinkingEnabled|thinking_toggle|chat-detail-thinking-toggle|reasoningTip|no_think' web agent api rag -S

echo '--- inspect web message-input toggle section ---'
sed -n '230,280p' web/src/components/message-input/next.tsx

echo '--- inspect web locale text around reasoning tip ---'
sed -n '1110,1145p' web/src/locales/en.ts

Repository: infiniflow/ragflow

Length of output: 16989


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- LLMBundle class and backend selection ---'
rg -n "class LLMBundle|backend\s*=|SupportedLiteLLMProvider|_apply_model_family_policies" api/db/services/llm_service.py rag/llm/chat_model.py -A 12 -B 12

echo '--- agent component thinking parameter definition search ---'
rg -n "thinking" agent/component agent/templates web/src -S | head -n 120

Repository: infiniflow/ragflow

Length of output: 32471


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- search for thinking field assignment in agent code ---'
rg -n "\bthinking\b\s*[:=]" agent api rag web/src -S

echo '--- component param base and serialization ---'
sed -n '1,260p' agent/component/base.py

echo '--- agent llm component around any config form metadata ---'
rg -n "get_input_form|get_input_elements|gen_conf\(" agent/component/llm.py agent/component/base.py -A 8 -B 8

Repository: infiniflow/ragflow

Length of output: 23894


Map thinking to the adapter contract before calling the bundle. self.thinking is forwarded verbatim here, but rag/llm/chat_model.py only normalizes reasoning for kimi-k2.5 and otherwise drops thinking. If agent configs can set this field, it won’t reach downstream in the shape the model adapters expect.

🤖 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/llm.py` around lines 80 - 81, Map the agent-level thinking
setting to the adapter’s expected contract before building conf in the LLM
component. In the logic around the self.thinking check, normalize/translate the
field so downstream adapters receive the shape they expect (for example, align
it with the reasoning handling used in rag/llm/chat_model.py rather than
forwarding thinking verbatim). Update the configuration assembly in the relevant
llm model class so bundle calls always get the adapter-compatible key/value.

@AI-Mart

AI-Mart commented Jul 5, 2026

Copy link
Copy Markdown
Contributor Author

🙏 Friendly Bump — This PR is Ready to Merge

This is a 3-line fix that completes an already-tested code path for a highly requested feature.

Why this matters

  • Qwen3.6-27B (and full Qwen3 family) are increasingly used in RAGFlow Agent workflows
  • Different agent nodes need different modes: reasoning nodes need thinking ON, simple Q&A nodes need thinking OFF
  • The UI already has the thinking dropdown (default/enabled/disabled) — it just doesn't reach the backend
  • _apply_model_family_policies() in rag/llm/chat_model.py already handles enable_thinking for Qwen3 — this PR only bridges the missing link in gen_conf()

Test coverage already exists

See test/unit_test/rag/llm/test_chat_model_thinking_policy.py — Qwen3 thinking policy is already unit-tested.

Related issues

Both are addressed by this PR. Please consider merging. Happy to address any feedback!

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jul 6, 2026
@yuzhichang yuzhichang added the ci Continue Integration label Jul 6, 2026
@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (e6dd397) to head (d7e21d5).
⚠️ Report is 811 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16640      +/-   ##
==========================================
- Coverage   94.53%   93.16%   -1.37%     
==========================================
  Files          10       10              
  Lines         713      717       +4     
  Branches      116      118       +2     
==========================================
- Hits          674      668       -6     
- Misses         25       29       +4     
- Partials       14       20       +6     

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

@yuzhichang
yuzhichang merged commit fe2f3b6 into infiniflow:main Jul 6, 2026
15 checks passed
@dosubot dosubot Bot mentioned this pull request Jul 7, 2026
4 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. lgtm This PR has been approved by a maintainer size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

2 participants