Skip to content

Feat/agent thinking switch - #15446

Merged
yuzhichang merged 6 commits into
infiniflow:mainfrom
jiashi19:feat/agent-thinking-switch
Jun 28, 2026
Merged

yuzhichang merged 6 commits into
infiniflow:mainfrom
jiashi19:feat/agent-thinking-switch

Conversation

@jiashi19

@jiashi19 jiashi19 commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

This PR adds an Agent LLM setting to control thinking mode for official providers that expose a thinking switch.

Related to #12842.
Closes #15445.

Some providers expose thinking controls through provider-specific request fields, but Agent LLM settings did not have a unified option for users to enable or disable thinking mode.

This PR adds a Thinking selector with:

  • System default
  • Enabled
  • Disabled
8566b0b4-0546-4c8a-913d-f9bbd38319f6 8a0a6bee-f45f-48d5-bd83-17af260de3db Initial support is limited to the verified official providers:
  • Qwen / DashScope: enable_thinking
  • Kimi / Moonshot: thinking.type
  • GLM / ZHIPU-AI: thinking.type

For LiteLLM-based providers, provider-specific fields are forwarded through extra_body before drop_params filtering so the request parameters are preserved.

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. labels May 30, 2026
@coderabbitai

coderabbitai Bot commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a user-controllable "thinking" mode to Agent LLM params, normalizes it per model family at request time, maps it into provider-specific payloads (including LiteLLM extra_body routing), adds frontend options and translations, and includes unit tests for mappings and field movement.

Changes

LLM Thinking Mode Control

Layer / File(s) Summary
Agent parameter and config emission
agent/component/llm.py
LLMParam adds thinking and emits it in gen_conf() when set to enabled or disabled.
Model-family policies and provider mapping
rag/llm/chat_model.py
Normalizes thinking/enable_thinking into a tri-state and maps to provider-specific payloads for Qwen3, Moonshot/Kimi, and ZHIPU GLM. Adds _move_litellm_provider_body_fields to relocate provider fields into extra_body.
Config filtering and request-time policy application
rag/llm/chat_model.py
Base._clean_conf limits gen_conf to the allowed key set; async request methods apply _apply_model_family_policies at call time and merge returned extra request kwargs (streams propagate stop).
LiteLLM completion args
rag/llm/chat_model.py
_construct_completion_args moves provider-specific thinking fields into completion_args["extra_body"].
Test stubs and policy coverage
test/unit_test/rag/llm/conftest.py, test/unit_test/rag/llm/test_chat_model_thinking_policy.py, test/unit_test/rag/llm/test_clean_conf_whitelist.py
Adds SupportedLiteLLMProvider and constants to test stub and tests covering Qwen3 defaults/explicit behavior, LiteLLM provider routing, Kimi/Moonshot mappings and defaults, ZHIPU GLM behavior, _move_litellm_provider_body_fields merging, and _clean_conf whitelist behavior.
Frontend selector and translations
web/src/components/llm-setting-items/next.tsx, web/src/locales/*
Adds thinking to showFields and schema, renders Select with default/enabled/disabled, and inserts English, Traditional Chinese, and Simplified Chinese translation keys.

Sequence Diagram

sequenceDiagram
  participant AgentParam
  participant ChatModel._apply_model_family_policies
  participant OpenAI_Base
  participant LiteLLM_Construct
  AgentParam->>ChatModel._apply_model_family_policies: gen_conf() (may include thinking)
  ChatModel._apply_model_family_policies->>OpenAI_Base: return gen_conf, extra_request_kwargs (extra_body)
  ChatModel._apply_model_family_policies->>LiteLLM_Construct: return sanitized_gen_conf (provider thinking fields)
  OpenAI_Base->>Provider: call with merged request kwargs
  LiteLLM_Construct->>Provider: completion_args with extra_body.thinking
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

  • infiniflow/ragflow#15432: Changes to gen-conf sanitization and allowlist handling related to forwarding thinking/enable_thinking.
  • infiniflow/ragflow#14566: Modifications in chat-path methods that also adjust gen_conf handling and defensive copies.

Suggested labels

🧪 test, size:M

Poem

🐰 I hop through code with a curious grin,
toggling thinking so models can begin,
params whisper downstream into provider nests,
UI picks options and tests do the rest,
carrots of coverage keep regressions thin.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.82% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Feat/agent thinking switch' directly corresponds to the main feature being added: a thinking mode switch for Agent LLM settings across multiple providers.
Description check ✅ Passed The PR description covers all required template sections: clearly states the problem (lack of unified thinking control), identifies the type of change (New Feature), and includes implementation details with UI screenshots.
Linked Issues check ✅ Passed All key requirements from #15445 are implemented: a Thinking selector with three options, support for Qwen/DashScope/Kimi/Moonshot/GLM providers, internal field mapping to provider-specific formats, and extra_body forwarding for LiteLLM providers.
Out of Scope Changes check ✅ Passed All code changes directly support the thinking mode feature: backend LLM param handling, provider policy routing, test coverage, and UI/locale updates. No unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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: 2

Caution

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

⚠️ Outside diff range comments (2)
web/src/components/llm-setting-items/next.tsx (1)

56-64: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Constrain thinking to UI-backed values in LlmSettingFieldSchema (client-side validation)

Backend only accepts thinking values enabled/disabled (other values resolve to None/default via _thinking_type and agent/component/llm.py), so the risk of unsupported values reaching the provider is low—but the schema should still match the UI options to prevent invalid/unsanctioned values from being validated/persisted.

♻️ Proposed fix
 export const LlmSettingFieldSchema = {
   temperature: z.coerce.number().optional(),
   top_p: z.number().optional(),
   presence_penalty: z.coerce.number().optional(),
   frequency_penalty: z.coerce.number().optional(),
   max_tokens: z.number().optional(),
   parameter: z.string().optional(),
-  thinking: z.string().optional(),
+  thinking: z.enum(['default', 'enabled', 'disabled']).optional(),
 };
🤖 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 `@web/src/components/llm-setting-items/next.tsx` around lines 56 - 64, The
LlmSettingFieldSchema's thinking field currently allows any string; restrict it
to the UI-backed choices by replacing thinking: z.string().optional() with an
enum that only accepts "enabled" and "disabled" (e.g., thinking:
z.enum(['enabled','disabled']).optional()) so client-side validation matches the
UI and prevents invalid values from being persisted; update any related
types/imports if necessary.
rag/llm/chat_model.py (1)

618-618: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fallback tool-stream request drops policy-derived kwargs

Line 618 builds the max-round fallback request without extra_request_kwargs, so provider-specific routed fields can be lost in that branch.

Suggested fix
-                response = await self.async_client.chat.completions.create(model=self.model_name, messages=history, stream=True, tools=tools, tool_choice="auto", **gen_conf)
+                response = await self.async_client.chat.completions.create(
+                    model=self.model_name,
+                    messages=history,
+                    stream=True,
+                    tools=tools,
+                    tool_choice="auto",
+                    **gen_conf,
+                    **extra_request_kwargs,
+                )
🤖 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 `@rag/llm/chat_model.py` at line 618, The fallback stream call to
async_client.chat.completions.create (the line building the max-round fallback
request) is missing provider-specific extra_request_kwargs, which causes routed
fields to be dropped; update the call in the chat model (where response = await
self.async_client.chat.completions.create(model=self.model_name,
messages=history, stream=True, tools=tools, tool_choice="auto", **gen_conf)) to
forward extra_request_kwargs as well (e.g., merge or pass extra_request_kwargs
alongside gen_conf), ensuring any provider-specific fields from
self.extra_request_kwargs are included in that fallback request.
🧹 Nitpick comments (1)
rag/llm/chat_model.py (1)

65-163: ⚡ Quick win

Add debug logging around thinking-policy routing decisions

The new policy path resolves and transforms provider-specific request fields, but there is no targeted log for what policy was applied. A lightweight debug log at policy-application points would make rollout/debug much safer.

As per coding guidelines **/*.py: Add logging for new flows.

🤖 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 `@rag/llm/chat_model.py` around lines 65 - 163, The PR adds model-family policy
routing but lacks debug logs; add lightweight debug logging using a module-level
logger (logger = logging.getLogger(__name__)) inside
_apply_model_family_policies and _move_litellm_provider_body_fields to record
key decisions and mutations (e.g., in _apply_model_family_policies log
model_name, backend, provider, thinking_type and when you take the qwen3 branch,
when you set sanitized_gen_conf["enable_thinking"] vs extra_body, and when each
provider-specific branch (HunYuan, Moonshot, ZHIPU_AI, OpenAI/ Azure gpt-5)
mutates sanitized_gen_conf/sanitized_kwargs), and in
_move_litellm_provider_body_fields log provider and which keys were moved into
extra_body; keep messages concise and use logger.debug with the relevant
variables to aid debugging.
🤖 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 `@rag/llm/chat_model.py`:
- Around line 99-109: The current Qwen3 branch unconditionally sets
enable_thinking to False when thinking_type is falsy, preventing provider
defaults from applying; update the logic in the "qwen3" branch so you only set
enable_thinking when thinking_type is explicitly provided (i.e., compute
enable_thinking = (thinking_type == "enabled") only if thinking_type is not
None/empty), and otherwise do not write "enable_thinking" into
sanitized_gen_conf or sanitized_kwargs; modify the block handling
backend/provider (symbols: model_name_lower, thinking_type, enable_thinking,
sanitized_gen_conf, sanitized_kwargs, _merge_extra_body,
SupportedLiteLLMProvider, provider, backend) to skip injecting the flag when
thinking_type is not specified so provider defaults can pass through.

In `@test/unit_test/rag/llm/test_chat_model_thinking_policy.py`:
- Around line 21-138: Add pytest priority markers to each test in this file:
ensure pytest is imported and decorate the test functions (e.g.,
test_qwen3_uses_existing_disabled_default,
test_qwen3_can_enable_thinking_explicitly,
test_dashscope_litellm_qwen3_uses_provider_field,
test_kimi_thinking_maps_to_moonshot_payload,
test_moonshot_explicit_thinking_does_not_require_exact_kimi_model_name,
test_kimi_keeps_existing_enabled_default,
test_glm_thinking_maps_to_zhipu_payload,
test_litellm_provider_body_fields_move_to_extra_body_before_drop_params, and
test_litellm_provider_body_fields_preserve_existing_extra_body) with the
appropriate priority marker (`@pytest.mark.p1/p2/p3`) per project guidelines; add
a single import line "import pytest" at the top if not already present and apply
the chosen marker consistently across these tests.

---

Outside diff comments:
In `@rag/llm/chat_model.py`:
- Line 618: The fallback stream call to async_client.chat.completions.create
(the line building the max-round fallback request) is missing provider-specific
extra_request_kwargs, which causes routed fields to be dropped; update the call
in the chat model (where response = await
self.async_client.chat.completions.create(model=self.model_name,
messages=history, stream=True, tools=tools, tool_choice="auto", **gen_conf)) to
forward extra_request_kwargs as well (e.g., merge or pass extra_request_kwargs
alongside gen_conf), ensuring any provider-specific fields from
self.extra_request_kwargs are included in that fallback request.

In `@web/src/components/llm-setting-items/next.tsx`:
- Around line 56-64: The LlmSettingFieldSchema's thinking field currently allows
any string; restrict it to the UI-backed choices by replacing thinking:
z.string().optional() with an enum that only accepts "enabled" and "disabled"
(e.g., thinking: z.enum(['enabled','disabled']).optional()) so client-side
validation matches the UI and prevents invalid values from being persisted;
update any related types/imports if necessary.

---

Nitpick comments:
In `@rag/llm/chat_model.py`:
- Around line 65-163: The PR adds model-family policy routing but lacks debug
logs; add lightweight debug logging using a module-level logger (logger =
logging.getLogger(__name__)) inside _apply_model_family_policies and
_move_litellm_provider_body_fields to record key decisions and mutations (e.g.,
in _apply_model_family_policies log model_name, backend, provider, thinking_type
and when you take the qwen3 branch, when you set
sanitized_gen_conf["enable_thinking"] vs extra_body, and when each
provider-specific branch (HunYuan, Moonshot, ZHIPU_AI, OpenAI/ Azure gpt-5)
mutates sanitized_gen_conf/sanitized_kwargs), and in
_move_litellm_provider_body_fields log provider and which keys were moved into
extra_body; keep messages concise and use logger.debug with the relevant
variables to aid debugging.
🪄 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: 968f1386-43d0-4004-b228-c38d124bbe5c

📥 Commits

Reviewing files that changed from the base of the PR and between cd18cfa and 17df4b8.

📒 Files selected for processing (8)
  • agent/component/llm.py
  • rag/llm/chat_model.py
  • test/unit_test/rag/llm/conftest.py
  • test/unit_test/rag/llm/test_chat_model_thinking_policy.py
  • web/src/components/llm-setting-items/next.tsx
  • web/src/locales/en.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts

Comment thread rag/llm/chat_model.py Outdated
Comment on lines 99 to 109
# Qwen3 keeps the existing default of disabling thinking unless explicitly overridden.
if "qwen3" in model_name_lower:
sanitized_kwargs["extra_body"] = {"enable_thinking": False}
enable_thinking = thinking_type == "enabled" if thinking_type else False
if backend == "litellm" and provider in {
SupportedLiteLLMProvider.Tongyi_Qianwen,
SupportedLiteLLMProvider.Dashscope,
}:
sanitized_gen_conf["enable_thinking"] = enable_thinking
else:
_merge_extra_body(sanitized_kwargs, {"enable_thinking": enable_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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Provider-default thinking is being overridden to disabled for Qwen3

Line 101 forces enable_thinking=False when no explicit thinking is set, so “Provider default” cannot pass through for Qwen3.

Suggested fix
     # Qwen3 keeps the existing default of disabling thinking unless explicitly overridden.
     if "qwen3" in model_name_lower:
-        enable_thinking = thinking_type == "enabled" if thinking_type else False
-        if backend == "litellm" and provider in {
-            SupportedLiteLLMProvider.Tongyi_Qianwen,
-            SupportedLiteLLMProvider.Dashscope,
-        }:
-            sanitized_gen_conf["enable_thinking"] = enable_thinking
-        else:
-            _merge_extra_body(sanitized_kwargs, {"enable_thinking": enable_thinking})
+        if thinking_type is not None:
+            enable_thinking = thinking_type == "enabled"
+            if backend == "litellm" and provider in {
+                SupportedLiteLLMProvider.Tongyi_Qianwen,
+                SupportedLiteLLMProvider.Dashscope,
+            }:
+                sanitized_gen_conf["enable_thinking"] = enable_thinking
+            else:
+                _merge_extra_body(sanitized_kwargs, {"enable_thinking": enable_thinking})
🤖 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 `@rag/llm/chat_model.py` around lines 99 - 109, The current Qwen3 branch
unconditionally sets enable_thinking to False when thinking_type is falsy,
preventing provider defaults from applying; update the logic in the "qwen3"
branch so you only set enable_thinking when thinking_type is explicitly provided
(i.e., compute enable_thinking = (thinking_type == "enabled") only if
thinking_type is not None/empty), and otherwise do not write "enable_thinking"
into sanitized_gen_conf or sanitized_kwargs; modify the block handling
backend/provider (symbols: model_name_lower, thinking_type, enable_thinking,
sanitized_gen_conf, sanitized_kwargs, _merge_extra_body,
SupportedLiteLLMProvider, provider, backend) to skip injecting the flag when
thinking_type is not specified so provider defaults can pass through.

@jiashi19
jiashi19 force-pushed the feat/agent-thinking-switch branch from 17df4b8 to b90c56d Compare June 2, 2026 06:09

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

Caution

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

⚠️ Outside diff range comments (1)
rag/llm/chat_model.py (1)

633-636: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Carry extra_request_kwargs into the max-rounds fallback.

This fallback request drops the provider-specific kwargs computed earlier. For base Qwen/DashScope calls, that means the injected extra_body.enable_thinking disappears exactly on the branch that runs after max_rounds is exceeded.

Suggested fix
-                response = await self.async_client.chat.completions.create(model=self.model_name, messages=history, stream=True, tools=tools, tool_choice="auto", **gen_conf)
+                response = await self.async_client.chat.completions.create(
+                    model=self.model_name,
+                    messages=history,
+                    stream=True,
+                    tools=tools,
+                    tool_choice="auto",
+                    **gen_conf,
+                    **extra_request_kwargs,
+                )
🤖 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 `@rag/llm/chat_model.py` around lines 633 - 636, The max-rounds fallback call
to self.async_client.chat.completions.create in the branch that appends "Exceed
max rounds" omits the provider-specific extra_request_kwargs computed earlier;
update that fallback invocation (the call using model=self.model_name,
messages=history, stream=True, tools=tools, tool_choice="auto", **gen_conf) to
also include **extra_request_kwargs so provider-specific flags like
extra_body.enable_thinking are preserved when the max-rounds branch runs.
🧹 Nitpick comments (1)
rag/llm/chat_model.py (1)

188-206: ⚡ Quick win

Add debug logging for provider-field rewrites.

This new helper silently moves request parameters into extra_body. When a provider rejects a request, there is no trace of which fields were rewritten, which makes the new thinking-mode flow hard to diagnose.

Suggested fix
 def _move_litellm_provider_body_fields(provider: SupportedLiteLLMProvider | str | None, completion_args: dict) -> dict:
     provider_body_fields = {
         SupportedLiteLLMProvider.Tongyi_Qianwen: {"enable_thinking"},
         SupportedLiteLLMProvider.Dashscope: {"enable_thinking"},
         SupportedLiteLLMProvider.Moonshot: {"thinking"},
         SupportedLiteLLMProvider.ZHIPU_AI: {"thinking"},
     }.get(provider, set())

     body = completion_args.get("extra_body")
     if not isinstance(body, dict):
         body = {}
     moved = False
+    moved_keys = []
     for key in provider_body_fields:
         if key in completion_args:
             body[key] = completion_args.pop(key)
             moved = True
+            moved_keys.append(key)
     if moved or body:
         completion_args["extra_body"] = body
+    if moved_keys:
+        logging.debug(
+            "Moved LiteLLM provider fields into extra_body: provider=%s keys=%s",
+            provider,
+            sorted(moved_keys),
+        )
     return completion_args

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 `@rag/llm/chat_model.py` around lines 188 - 206, The helper
_move_litellm_provider_body_fields currently mutates completion_args silently;
add debug logging that records the provider, which keys were moved, their
original values, and the resulting extra_body to aid debugging when providers
reject requests. Inside _move_litellm_provider_body_fields (use provider and
completion_args to identify the context), obtain a module logger (e.g.,
logging.getLogger(__name__)) and log at DEBUG when any key from
provider_body_fields is found and moved, including a list of moved keys and a
snapshot of their values and the final completion_args["extra_body"]; also log
when extra_body existed but no keys were moved to show no-op rewrites. Ensure
logs avoid leaking sensitive data if applicable.
🤖 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.

Outside diff comments:
In `@rag/llm/chat_model.py`:
- Around line 633-636: The max-rounds fallback call to
self.async_client.chat.completions.create in the branch that appends "Exceed max
rounds" omits the provider-specific extra_request_kwargs computed earlier;
update that fallback invocation (the call using model=self.model_name,
messages=history, stream=True, tools=tools, tool_choice="auto", **gen_conf) to
also include **extra_request_kwargs so provider-specific flags like
extra_body.enable_thinking are preserved when the max-rounds branch runs.

---

Nitpick comments:
In `@rag/llm/chat_model.py`:
- Around line 188-206: The helper _move_litellm_provider_body_fields currently
mutates completion_args silently; add debug logging that records the provider,
which keys were moved, their original values, and the resulting extra_body to
aid debugging when providers reject requests. Inside
_move_litellm_provider_body_fields (use provider and completion_args to identify
the context), obtain a module logger (e.g., logging.getLogger(__name__)) and log
at DEBUG when any key from provider_body_fields is found and moved, including a
list of moved keys and a snapshot of their values and the final
completion_args["extra_body"]; also log when extra_body existed but no keys were
moved to show no-op rewrites. Ensure logs avoid leaking sensitive data if
applicable.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cfeb4962-f101-4e55-a80b-b7176dcf3796

📥 Commits

Reviewing files that changed from the base of the PR and between 17df4b8 and b90c56d.

📒 Files selected for processing (8)
  • agent/component/llm.py
  • rag/llm/chat_model.py
  • test/unit_test/rag/llm/conftest.py
  • test/unit_test/rag/llm/test_chat_model_thinking_policy.py
  • web/src/components/llm-setting-items/next.tsx
  • web/src/locales/en.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts
✅ Files skipped from review due to trivial changes (1)
  • web/src/locales/zh-traditional.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • web/src/components/llm-setting-items/next.tsx
  • web/src/locales/zh.ts
  • test/unit_test/rag/llm/conftest.py
  • agent/component/llm.py
  • test/unit_test/rag/llm/test_chat_model_thinking_policy.py

@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)
test/unit_test/rag/llm/test_chat_model_thinking_policy.py (1)

49-60: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Exercise the actual DashScope provider branch.

Line 53 passes SupportedLiteLLMProvider.Tongyi_Qianwen, so this test never hits the separate SupportedLiteLLMProvider.Dashscope enum path in _apply_model_family_policies(). A regression isolated to DashScope would still pass.

Proposed fix
-def test_dashscope_litellm_qwen3_uses_provider_field():
+@pytest.mark.parametrize(
+    "provider",
+    [SupportedLiteLLMProvider.Tongyi_Qianwen, SupportedLiteLLMProvider.Dashscope],
+)
+def test_qwen3_litellm_provider_uses_provider_field(provider):
     gen_conf, kwargs = _apply_model_family_policies(
         "qwen3-max",
         backend="litellm",
-        provider=SupportedLiteLLMProvider.Tongyi_Qianwen,
+        provider=provider,
         gen_conf={"thinking": "disabled"},
         request_kwargs={},
     )

     assert kwargs == {}
     assert gen_conf["enable_thinking"] is False
🤖 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 `@test/unit_test/rag/llm/test_chat_model_thinking_policy.py` around lines 49 -
60, The test test_dashscope_litellm_qwen3_uses_provider_field currently passes
SupportedLiteLLMProvider.Tongyi_Qianwen so it never exercises the Dashscope
branch; update this test to pass SupportedLiteLLMProvider.Dashscope (or the
exact Dashscope enum member name used in the code) when calling
_apply_model_family_policies("qwen3-max", backend="litellm", provider=...), keep
the same assertions for kwargs and gen_conf["enable_thinking"], and ensure the
test name still reflects Dashscope to confirm the DashScope-specific logic is
exercised.
🤖 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 `@test/unit_test/rag/llm/test_chat_model_thinking_policy.py`:
- Around line 89-100: Update the
test_kimi_keeps_provider_default_when_unspecified unit test to assert the actual
provider-default thinking payload produced by _apply_model_family_policies (not
just that keys are absent): call _apply_model_family_policies with
provider=SupportedLiteLLMProvider.Moonshot and then assert gen_conf["thinking"]
equals the expected default dict (including top_p, n, presence_penalty,
frequency_penalty and any other provider-injected fields) and continue asserting
kwargs == {} and that temperature was removed; reference the test function name
and the helper _apply_model_family_policies to locate where to add/replace the
assertions.

---

Outside diff comments:
In `@test/unit_test/rag/llm/test_chat_model_thinking_policy.py`:
- Around line 49-60: The test test_dashscope_litellm_qwen3_uses_provider_field
currently passes SupportedLiteLLMProvider.Tongyi_Qianwen so it never exercises
the Dashscope branch; update this test to pass
SupportedLiteLLMProvider.Dashscope (or the exact Dashscope enum member name used
in the code) when calling _apply_model_family_policies("qwen3-max",
backend="litellm", provider=...), keep the same assertions for kwargs and
gen_conf["enable_thinking"], and ensure the test name still reflects Dashscope
to confirm the DashScope-specific logic is exercised.
🪄 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: cde29feb-b397-432a-aa19-6616176d2140

📥 Commits

Reviewing files that changed from the base of the PR and between b90c56d and 95cb8d4.

📒 Files selected for processing (6)
  • rag/llm/chat_model.py
  • test/unit_test/rag/llm/test_chat_model_thinking_policy.py
  • web/src/components/llm-setting-items/next.tsx
  • web/src/locales/en.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts
✅ Files skipped from review due to trivial changes (1)
  • web/src/locales/zh.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • web/src/locales/zh-traditional.ts
  • web/src/components/llm-setting-items/next.tsx
  • web/src/locales/en.ts

@jiashi19

jiashi19 commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

@yingfeng could you please review this PR?

@yingfeng
yingfeng requested a review from buua436 June 8, 2026 03:28
@yingfeng yingfeng added the ci Continue Integration label Jun 8, 2026
@yingfeng
yingfeng marked this pull request as draft June 8, 2026 08:53
@yingfeng
yingfeng marked this pull request as ready for review June 8, 2026 08:53

@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 `@test/unit_test/rag/llm/test_clean_conf_whitelist.py`:
- Around line 88-93: Add the required pytest priority marker to the new test
functions so they follow the repo convention: import pytest at the top if not
already present and annotate test_base_drops_litellm_reasoning_controls with an
appropriate marker (e.g., `@pytest.mark.p2`); do the same for the other new test
added around lines 122-129 (identify it by its test function name) so both tests
use the p1/p2/p3 marker convention.
🪄 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: 9cbf495e-0eec-47f1-8fc4-8803a70490ca

📥 Commits

Reviewing files that changed from the base of the PR and between 429cdc2 and b9e646a.

📒 Files selected for processing (2)
  • rag/llm/chat_model.py
  • test/unit_test/rag/llm/test_clean_conf_whitelist.py

Comment on lines +88 to +93
def test_base_drops_litellm_reasoning_controls():
cleaned = _make_base()._clean_conf({"temperature": 0.5, "thinking": {"type": "enabled"}, "enable_thinking": True})
assert "thinking" not in cleaned
assert "enable_thinking" not in cleaned
assert cleaned["temperature"] == 0.5

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add required pytest priority markers to new tests.

Line 88 and Line 122 add new test cases without the required p1/p2/p3 marker convention for test/**/*.py. Please annotate these tests (for example, @pytest.mark.p2) to match repository test policy.

Suggested patch
+@pytest.mark.p2
 def test_base_drops_litellm_reasoning_controls():
     cleaned = _make_base()._clean_conf({"temperature": 0.5, "thinking": {"type": "enabled"}, "enable_thinking": True})
     assert "thinking" not in cleaned
     assert "enable_thinking" not in cleaned
     assert cleaned["temperature"] == 0.5
@@
+@pytest.mark.p2
 def test_litellm_preserves_provider_mapped_thinking_param():
     """Provider-mapped ``thinking`` must survive the LiteLLM whitelist."""
     cleaned = _make_litellm(
         "kimi-k2.6-preview",
         SupportedLiteLLMProvider.Moonshot,
     )._clean_conf({"thinking": {"type": "enabled"}, "temperature": 1.0})
     assert cleaned["thinking"] == {"type": "enabled"}

As per coding guidelines: test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python testing.

Also applies to: 122-129

🤖 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 `@test/unit_test/rag/llm/test_clean_conf_whitelist.py` around lines 88 - 93,
Add the required pytest priority marker to the new test functions so they follow
the repo convention: import pytest at the top if not already present and
annotate test_base_drops_litellm_reasoning_controls with an appropriate marker
(e.g., `@pytest.mark.p2`); do the same for the other new test added around lines
122-129 (identify it by its test function name) so both tests use the p1/p2/p3
marker convention.

Source: Coding guidelines

@codecov

codecov Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (f90be41) to head (cec4e00).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #15446      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- 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.

jiashi19 added 5 commits June 23, 2026 11:37
Add a Thinking selector to agent LLM settings so users can choose the
provider default behavior or explicitly enable/disable thinking mode.

This change currently supports only the official Qwen, Kimi, and GLM
model providers. The backend maps the shared agent setting to each
provider's supported request format:
- Qwen/DashScope: enable_thinking
- Kimi/Moonshot: thinking.type
- GLM/ZHIPU-AI: thinking.type
- Keep Qwen3 on RAGFlow's system default of disabled thinking unless explicitly enabled
- Preserve Kimi provider default while still removing unsupported temperature parameters
- Forward provider-specific kwargs in the tool-stream max-round fallback
- Restrict frontend thinking values to default/enabled/disabled
- Rename the UI option from provider default to system default
Only consume and rewrite thinking controls when the Qwen, Moonshot, or ZHIPU provider policies actually handle them. Keep existing LiteLLM passthrough behavior for generic thinking parameters.
Add regression coverage for generic LiteLLM thinking passthrough, provider-mapped Moonshot thinking payloads, and Base whitelist filtering.
@jiashi19
jiashi19 force-pushed the feat/agent-thinking-switch branch from 2dd4df0 to 0c433ab Compare June 23, 2026 06:50
@yuzhichang
yuzhichang self-requested a review June 28, 2026 00:50
@yuzhichang
yuzhichang merged commit db188cc into infiniflow:main Jun 28, 2026
3 checks passed
yuzhichang added a commit that referenced this pull request Jun 29, 2026
### What problem does this PR solve?

This PR adds an Agent LLM setting to control thinking mode for official
providers that expose a thinking switch.

Related to #12842.  
Closes #15445.

Some providers expose thinking controls through provider-specific
request fields, but Agent LLM settings did not have a unified option for
users to enable or disable thinking mode.

This PR adds a `Thinking` selector with:

- System default
- Enabled
- Disabled
<img width="452" height="278" alt="8566b0b4-0546-4c8a-913d-f9bbd38319f6"
src="https://github.com/user-attachments/assets/25b497f7-1ba0-4bfe-940d-6fe79287d6ab"
/>
<img width="471" height="971" alt="8a0a6bee-f45f-48d5-bd83-17af260de3db"
src="https://github.com/user-attachments/assets/41ad43c1-5087-48f1-bf37-f2ca14c2be2f"
/>
Initial support is limited to the verified official providers:

- Qwen / DashScope: `enable_thinking`
- Kimi / Moonshot: `thinking.type`
- GLM / ZHIPU-AI: `thinking.type`

For LiteLLM-based providers, provider-specific fields are forwarded
through `extra_body` before `drop_params` filtering so the request
parameters are preserved.



### Type of change

- [x] New Feature (non-breaking change which adds functionality)

---------

Co-authored-by: jiashi <[email protected]>
Co-authored-by: Zhichang Yu <[email protected]>
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 4 - API auth ports
- infiniflow#16169 Sandbox artifact ownership: add UserCanvasDAO.Accessible
  (owner-or-team predicate) and DocumentService.sandboxArtifactAccessible
  to gate GET /api/v1/documents/artifact/<filename>. Query
  API4Conversation for sessions owned by userID whose message blob
  references the filename (or its documents/artifact/<name> URL
  form); require at least one accessible canvas. Handler now
  fetches the current user and passes userID into the service;
  denial returns ErrArtifactNotFound to avoid cross-user
  enumeration.
- infiniflow#15457 Tenant ownership on agentbots: Go side already had the
  loadCanvas IDOR guard at the entry of both AgentbotInputs and
  AgentbotCompletion. Added a cross-tenant regression test
  (tenant-B asks for tenant-A's canvas -> ErrUserCanvasNotFound).
- infiniflow#15145 Rerun agent document access: add DocumentService.Accessible
  (loads doc, checks kbDAO.Accessible). Wire documentService into
  AgentHandler via WithDocumentService (nil-tolerant, preserves
  the existing NewAgentHandler signature for tests). RerunAgent
  returns "Document not found." when accessible check fails;
  cmd/server_main.go wires documentService after construction.

Group 2 - thinking switch
- infiniflow#15446 component portion: add Thinking field to LLMParam,
  LLMInput, and ChatInvokeRequest. mergeLLMParam reads
  inputs["thinking"] with a whitelist of {"enabled","disabled"}
  (matching python llm.py:78-79); arbitrary strings are
  rejected. The provider policy portion (Qwen/Kimi/GLM in
  rag/llm/chat_model.py) belongs to internal/llm/ and is a
  separate porting stream.

Total: 4 new tests across 3 modified test files. All touched
package tests pass (1697 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#16169 infiniflow#15457 infiniflow#15145 infiniflow#15446
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 4 - API auth ports
- infiniflow#16169 Sandbox artifact ownership: add UserCanvasDAO.Accessible
  (owner-or-team predicate) and DocumentService.sandboxArtifactAccessible
  to gate GET /api/v1/documents/artifact/<filename>. Query
  API4Conversation for sessions owned by userID whose message blob
  references the filename (or its documents/artifact/<name> URL
  form); require at least one accessible canvas. Handler now
  fetches the current user and passes userID into the service;
  denial returns ErrArtifactNotFound to avoid cross-user
  enumeration.
- infiniflow#15457 Tenant ownership on agentbots: Go side already had the
  loadCanvas IDOR guard at the entry of both AgentbotInputs and
  AgentbotCompletion. Added a cross-tenant regression test
  (tenant-B asks for tenant-A's canvas -> ErrUserCanvasNotFound).
- infiniflow#15145 Rerun agent document access: add DocumentService.Accessible
  (loads doc, checks kbDAO.Accessible). Wire documentService into
  AgentHandler via WithDocumentService (nil-tolerant, preserves
  the existing NewAgentHandler signature for tests). RerunAgent
  returns "Document not found." when accessible check fails;
  cmd/server_main.go wires documentService after construction.

Group 2 - thinking switch
- infiniflow#15446 component portion: add Thinking field to LLMParam,
  LLMInput, and ChatInvokeRequest. mergeLLMParam reads
  inputs["thinking"] with a whitelist of {"enabled","disabled"}
  (matching python llm.py:78-79); arbitrary strings are
  rejected. The provider policy portion (Qwen/Kimi/GLM in
  rag/llm/chat_model.py) belongs to internal/llm/ and is a
  separate porting stream.

Total: 4 new tests across 3 modified test files. All touched
package tests pass (1697 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#16169 infiniflow#15457 infiniflow#15145 infiniflow#15446
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 4 - API auth ports
- infiniflow#16169 Sandbox artifact ownership: add UserCanvasDAO.Accessible
  (owner-or-team predicate) and DocumentService.sandboxArtifactAccessible
  to gate GET /api/v1/documents/artifact/<filename>. Query
  API4Conversation for sessions owned by userID whose message blob
  references the filename (or its documents/artifact/<name> URL
  form); require at least one accessible canvas. Handler now
  fetches the current user and passes userID into the service;
  denial returns ErrArtifactNotFound to avoid cross-user
  enumeration.
- infiniflow#15457 Tenant ownership on agentbots: Go side already had the
  loadCanvas IDOR guard at the entry of both AgentbotInputs and
  AgentbotCompletion. Added a cross-tenant regression test
  (tenant-B asks for tenant-A's canvas -> ErrUserCanvasNotFound).
- infiniflow#15145 Rerun agent document access: add DocumentService.Accessible
  (loads doc, checks kbDAO.Accessible). Wire documentService into
  AgentHandler via WithDocumentService (nil-tolerant, preserves
  the existing NewAgentHandler signature for tests). RerunAgent
  returns "Document not found." when accessible check fails;
  cmd/server_main.go wires documentService after construction.

Group 2 - thinking switch
- infiniflow#15446 component portion: add Thinking field to LLMParam,
  LLMInput, and ChatInvokeRequest. mergeLLMParam reads
  inputs["thinking"] with a whitelist of {"enabled","disabled"}
  (matching python llm.py:78-79); arbitrary strings are
  rejected. The provider policy portion (Qwen/Kimi/GLM in
  rag/llm/chat_model.py) belongs to internal/llm/ and is a
  separate porting stream.

Total: 4 new tests across 3 modified test files. All touched
package tests pass (1697 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#16169 infiniflow#15457 infiniflow#15145 infiniflow#15446
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 29, 2026
Ports 4 M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md
Execution snapshot (all merged upstream) to the Go agent side.

Group 4 - API auth ports
- infiniflow#16169 Sandbox artifact ownership: add UserCanvasDAO.Accessible
  (owner-or-team predicate) and DocumentService.sandboxArtifactAccessible
  to gate GET /api/v1/documents/artifact/<filename>. Query
  API4Conversation for sessions owned by userID whose message blob
  references the filename (or its documents/artifact/<name> URL
  form); require at least one accessible canvas. Handler now
  fetches the current user and passes userID into the service;
  denial returns ErrArtifactNotFound to avoid cross-user
  enumeration.
- infiniflow#15457 Tenant ownership on agentbots: Go side already had the
  loadCanvas IDOR guard at the entry of both AgentbotInputs and
  AgentbotCompletion. Added a cross-tenant regression test
  (tenant-B asks for tenant-A's canvas -> ErrUserCanvasNotFound).
- infiniflow#15145 Rerun agent document access: add DocumentService.Accessible
  (loads doc, checks kbDAO.Accessible). Wire documentService into
  AgentHandler via WithDocumentService (nil-tolerant, preserves
  the existing NewAgentHandler signature for tests). RerunAgent
  returns "Document not found." when accessible check fails;
  cmd/server_main.go wires documentService after construction.

Group 2 - thinking switch
- infiniflow#15446 component portion: add Thinking field to LLMParam,
  LLMInput, and ChatInvokeRequest. mergeLLMParam reads
  inputs["thinking"] with a whitelist of {"enabled","disabled"}
  (matching python llm.py:78-79); arbitrary strings are
  rejected. The provider policy portion (Qwen/Kimi/GLM in
  rag/llm/chat_model.py) belongs to internal/llm/ and is a
  separate porting stream.

Total: 4 new tests across 3 modified test files. All touched
package tests pass (1697 + 4 skipped). The 1 failing test
(TestAgent_ReActExhaustsSteps) is the pre-existing flaky test
that also fails on the baseline without my changes.

Refs: .claude/plans/review-and-port-py-agent-changes.md
Refs: infiniflow#16169 infiniflow#15457 infiniflow#15145 infiniflow#15446
yuzhichang added a commit that referenced this pull request Jun 30, 2026
)

Mirrors 14 merged upstream PRs into the Go agent port.

PRs ported:
  - #15609 ExeSQL SSRF guard + DNS pin
  - #15436 HTTP timeout on external API tools
  - #16363 be_output restore + DeepL error path
  - #15644 switch no longer matches empty condition
  - #15374 session_id bind to path agent_id (DAO idor guard)
  - #16169 sandbox artifact ownership gate
  - #15457 tenant ownership on agentbots
  - #15145 rerun agent document access check
- #15446 thinking switch (component portion; provider policy lives in
internal/llm)
  - #15426 Invoke URL/proxy SSRF + DNS pin + no-redirects
  - #15238 agentbot thinking-logs beta endpoint
  - #14589 UserFillUp SSE event propagation
  - #14890 anonymous webhook opt-in
- #15068 PipelineChunker new component (text/file_ref/parser_id
dispatch; file-format extraction is a follow-up)

40 files, +2355 / -58 lines. 33 new tests, all targeted package suites
pass (1721 + 4 skipped); 1 pre-existing flaky test unrelated.
yuzhichang added a commit to ondery/ragflow that referenced this pull request Jul 1, 2026
…sion/user + input/output to Langfuse for agent runs

Rebuilt on current upstream/main after force-push; cherry-pick of the 7
PR-original commits collapsed into a single net diff to avoid conflicts
with intervening commits pulled in by repeated merges of upstream/main.

Original PR work (commits dropped during rebuild because their content
already lives on upstream/main or was a merge of upstream/main):
  c7339ae Enhance LLMService with token usage reporting
  0266cf0 Implement token usage tracking and Langfuse integration
  ab2b267 Include session_id in run_kwargs
  8bf937c Implement token usage tracking in chat model
  c955988 Enhance token tracking with context variables and functions
  3e88ed5 fix(agent): address CodeRabbit review on token usage tracking
  74b8c8c fix(agent): address CodeRabbit follow-up review

Forced-upstream duplicates dropped (already merged to main):
  70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405),
  730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410),
  c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436),
  ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609),
  2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985),
  bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426),
  4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145)

Plus 18 'Merge branch main into main' commits dropped (polluted topology).
yuzhichang added a commit to ondery/ragflow that referenced this pull request Jul 1, 2026
…sion/user + input/output to Langfuse for agent runs

Rebuilt on current upstream/main after force-push; cherry-pick of the 7
PR-original commits collapsed into a single net diff to avoid conflicts
with intervening commits pulled in by repeated merges of upstream/main.

Original PR work (commits dropped during rebuild because their content
already lives on upstream/main or was a merge of upstream/main):
  c7339ae Enhance LLMService with token usage reporting
  0266cf0 Implement token usage tracking and Langfuse integration
  ab2b267 Include session_id in run_kwargs
  8bf937c Implement token usage tracking in chat model
  c955988 Enhance token tracking with context variables and functions
  3e88ed5 fix(agent): address CodeRabbit review on token usage tracking
  74b8c8c fix(agent): address CodeRabbit follow-up review

Forced-upstream duplicates dropped (already merged to main):
  70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405),
  730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410),
  c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436),
  ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609),
  2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985),
  bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426),
  4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145)

Plus 18 'Merge branch main into main' commits dropped (polluted topology).

Co-authored-by: yzc <[email protected]>
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 1, 2026
…iniflow#16455)

Mirrors 14 merged upstream PRs into the Go agent port.

PRs ported:
  - infiniflow#15609 ExeSQL SSRF guard + DNS pin
  - infiniflow#15436 HTTP timeout on external API tools
  - infiniflow#16363 be_output restore + DeepL error path
  - infiniflow#15644 switch no longer matches empty condition
  - infiniflow#15374 session_id bind to path agent_id (DAO idor guard)
  - infiniflow#16169 sandbox artifact ownership gate
  - infiniflow#15457 tenant ownership on agentbots
  - infiniflow#15145 rerun agent document access check
- infiniflow#15446 thinking switch (component portion; provider policy lives in
internal/llm)
  - infiniflow#15426 Invoke URL/proxy SSRF + DNS pin + no-redirects
  - infiniflow#15238 agentbot thinking-logs beta endpoint
  - infiniflow#14589 UserFillUp SSE event propagation
  - infiniflow#14890 anonymous webhook opt-in
- infiniflow#15068 PipelineChunker new component (text/file_ref/parser_id
dispatch; file-format extraction is a follow-up)

40 files, +2355 / -58 lines. 33 new tests, all targeted package suites
pass (1721 + 4 skipped); 1 pre-existing flaky test unrelated.
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. 🌈 python Pull requests that update Python code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Add Agent thinking mode switch for Qwen, Kimi, and GLM

3 participants