Skip to content

feat: pass chat_template_kwargs through agent chat completion - #14542

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
jsdevninja:feat/agent-chat-template-kwargs-passthrough
May 22, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
jsdevninja:feat/agent-chat-template-kwargs-passthrough

Conversation

@jsdevninja

@jsdevninja jsdevninja commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

The agent API currently does not pass chat_template_kwargs to the underlying LLM call path, so clients cannot control template-level model behavior (such as thinking-mode toggles) when invoking /agents/chat/completion. This PR adds passthrough support for chat_template_kwargs across agent execution flows (session and non-session, streaming and non-streaming) by propagating it through canvas runtime state and into LLM invocation kwargs. This addresses the feature gap raised in Issue #14182.

Closes #14182

Type of change

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

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Apr 30, 2026
@coderabbitai

coderabbitai Bot commented Apr 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

chat_template_kwargs is threaded from API requests through service calls into Canvas.run (stored at sys.chat_template_kwargs) and consumed by the LLM component, which parses and merges those kwargs into streaming and generation calls.

Changes

Chat template passthrough

Layer / File(s) Summary
API & Service forwarding
api/apps/restful_apis/agent_api.py, api/db/services/canvas_service.py
API and service layers accept chat_template_kwargs and forward it to canvas.run using constructed run_kwargs, covering streaming and non-streaming paths.
Canvas globals storage
agent/canvas.py
Canvas.run conditionally writes chat_template_kwargs into self.globals under sys.chat_template_kwargs.
LLM retrieval & injection
agent/component/llm.py
Adds _get_chat_template_kwargs() to read/validate sys.chat_template_kwargs (dict or JSON string via json_repair) and merges resulting kwargs into _stream_output_async, _invoke_async, and _generate_async calls.

Sequence Diagram

sequenceDiagram
    actor Client
    participant API as agent_api._run_workflow_session
    participant Service as canvas_service.completion
    participant Canvas as Canvas.run
    participant LLM as agent.component.llm

    Client->>API: chat_completion(..., chat_template_kwargs)
    API->>Service: canvas.run(**run_kwargs)
    Service->>Canvas: canvas.run(**run_kwargs)
    Canvas->>Canvas: store sys.chat_template_kwargs
    Canvas->>LLM: trigger LLM calls
    LLM->>LLM: _get_chat_template_kwargs()
    LLM->>LLM: parse/validate and merge kwargs
    LLM-->>Canvas: generation/streamed output
    Canvas-->>Service: execution results
    Service-->>API: stream/return output
    API-->>Client: response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14596: Modifies agent runtime/streaming completion flow touching similar execution paths in agent_api.py.

Suggested labels

🐖api

Suggested reviewers

  • wangq8

Poem

🐰 I hop from API to Canvas bright,
Carrying kwargs in my flight,
Stored in globals, parsed with care,
LLM whispers them into the air,
A tiny tweak that makes thoughts light.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 Title accurately describes the main change: adding chat_template_kwargs passthrough to agent chat completion API.
Description check ✅ Passed Description covers problem statement, implementation approach, and links to Issue #14182. Type of change is properly marked as New Feature.
Linked Issues check ✅ Passed Changes implement the requested feature from Issue #14182: adding chat_template_kwargs parameter support across agent execution flows (session/non-session, streaming/non-streaming) to enable template-level model behavior control.
Out of Scope Changes check ✅ Passed All changes are directly related to propagating chat_template_kwargs through canvas and LLM components as specified in Issue #14182; 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 and usage tips.

@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/canvas.py (1)

403-407: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid truthiness-gating chat_template_kwargs; it can leak stale values across turns.

Line 403 only writes globals when the value is truthy. If a caller sends {} (or omits the field after a prior turn set it), sys.chat_template_kwargs is not refreshed and previous settings can persist unexpectedly.

Suggested fix
-        for k in kwargs.keys():
-            if k in ["query", "user_id", "files", "chat_template_kwargs"] and kwargs[k]:
+        for k in kwargs.keys():
+            if k in ["query", "user_id", "files"] and kwargs[k]:
                 if k == "files":
                     self.globals[f"sys.{k}"] = await self.get_files_async(kwargs[k], layout_recognize)
                 else:
                     self.globals[f"sys.{k}"] = kwargs[k]
+        if "chat_template_kwargs" in kwargs:
+            self.globals["sys.chat_template_kwargs"] = kwargs.get("chat_template_kwargs") or {}
+        else:
+            self.globals.pop("sys.chat_template_kwargs", None)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@agent/canvas.py` around lines 403 - 407, The current loop only sets
self.globals[f"sys.{k}"] when kwargs[k] is truthy, which lets falsy values like
{} for "chat_template_kwargs" leave stale data; change the logic so
"chat_template_kwargs" is written into self.globals whenever it is present in
kwargs (even if falsy). Concretely, in the loop that iterates the keys ["query",
"user_id", "files", "chat_template_kwargs"], check membership in kwargs and
special-case k == "chat_template_kwargs" to assign self.globals[f"sys.{k}"] =
kwargs[k] directly; keep the existing await self.get_files_async(kwargs[k],
layout_recognize) behavior for k == "files". Ensure you reference and update the
assignments around self.globals[f"sys.{k}"] and get_files_async accordingly.
🧹 Nitpick comments (2)
api/apps/restful_apis/agent_api.py (1)

993-995: ⚡ Quick win

Add lightweight logging when forwarding chat_template_kwargs in non-session SSE flow.

This new branch is operationally silent; a debug log (type + top-level keys only) would make rollout/debugging much easier.

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

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/agent_api.py` around lines 993 - 995, Add a lightweight
debug log when forwarding req["chat_template_kwargs"] into run_kwargs before
calling canvas.run so the non-session SSE flow is observable: in the branch that
checks req.get("chat_template_kwargs") and sets
run_kwargs["chat_template_kwargs"], emit a logger.debug (or processLogger.debug
consistent with surrounding code) that logs the type name and top-level keys of
the dict (e.g., f"forwarding chat_template_kwargs type={type(...).__name__}
keys={list(...).[:N]}") and ensure this is done only for non-session SSE flows;
update the code around run_kwargs, req, and canvas.run to add this single-line
debug statement.
api/db/services/canvas_service.py (1)

246-247: ⚡ Quick win

Add debug logging for the new chat_template_kwargs service passthrough.

The new session/service flow now accepts and forwards this field, but there’s no visibility when it is present. Log only metadata (e.g., type/keys), not raw values.

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

Also applies to: 279-288

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/db/services/canvas_service.py` around lines 246 - 247, Add debug logging
when the service reads and forwards the new chat_template_kwargs passthrough:
after the assignment to chat_template_kwargs and in the later block that
forwards it (the region around the custom_header assignment and the subsequent
forwarding at lines ~279-288), emit a debug-level log using the module/service
logger (e.g., logger or service logger already used in this file) that records
only metadata — the type(chat_template_kwargs) and
list(chat_template_kwargs.keys()) if it's a dict — and only when
chat_template_kwargs is truthy; do not include any raw values, and guard the
logging with an if to avoid extra cost when absent. Ensure the log message is
concise and clearly identifies the context (e.g., "received
chat_template_kwargs" / "forwarding chat_template_kwargs").
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@agent/component/llm.py`:
- Around line 451-454: _get_chat_template_kwargs currently calls
self._canvas.get_variable_value("sys.chat_template_kwargs") which can raise
KeyError when the global is unset (because get_variable_value indexes
self.globals); wrap that call in a try/except KeyError (or test existence first)
and return {} on KeyError so LLM execution doesn't break, i.e., catch KeyError
raised by get_variable_value for "sys.chat_template_kwargs" inside
_get_chat_template_kwargs and fall back to an empty dict.

---

Outside diff comments:
In `@agent/canvas.py`:
- Around line 403-407: The current loop only sets self.globals[f"sys.{k}"] when
kwargs[k] is truthy, which lets falsy values like {} for "chat_template_kwargs"
leave stale data; change the logic so "chat_template_kwargs" is written into
self.globals whenever it is present in kwargs (even if falsy). Concretely, in
the loop that iterates the keys ["query", "user_id", "files",
"chat_template_kwargs"], check membership in kwargs and special-case k ==
"chat_template_kwargs" to assign self.globals[f"sys.{k}"] = kwargs[k] directly;
keep the existing await self.get_files_async(kwargs[k], layout_recognize)
behavior for k == "files". Ensure you reference and update the assignments
around self.globals[f"sys.{k}"] and get_files_async accordingly.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 993-995: Add a lightweight debug log when forwarding
req["chat_template_kwargs"] into run_kwargs before calling canvas.run so the
non-session SSE flow is observable: in the branch that checks
req.get("chat_template_kwargs") and sets run_kwargs["chat_template_kwargs"],
emit a logger.debug (or processLogger.debug consistent with surrounding code)
that logs the type name and top-level keys of the dict (e.g., f"forwarding
chat_template_kwargs type={type(...).__name__} keys={list(...).[:N]}") and
ensure this is done only for non-session SSE flows; update the code around
run_kwargs, req, and canvas.run to add this single-line debug statement.

In `@api/db/services/canvas_service.py`:
- Around line 246-247: Add debug logging when the service reads and forwards the
new chat_template_kwargs passthrough: after the assignment to
chat_template_kwargs and in the later block that forwards it (the region around
the custom_header assignment and the subsequent forwarding at lines ~279-288),
emit a debug-level log using the module/service logger (e.g., logger or service
logger already used in this file) that records only metadata — the
type(chat_template_kwargs) and list(chat_template_kwargs.keys()) if it's a dict
— and only when chat_template_kwargs is truthy; do not include any raw values,
and guard the logging with an if to avoid extra cost when absent. Ensure the log
message is concise and clearly identifies the context (e.g., "received
chat_template_kwargs" / "forwarding chat_template_kwargs").
🪄 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: a3f6c61b-5419-437d-b874-81c302b12640

📥 Commits

Reviewing files that changed from the base of the PR and between 5fd4579 and 7bcdc0e.

📒 Files selected for processing (4)
  • agent/canvas.py
  • agent/component/llm.py
  • api/apps/restful_apis/agent_api.py
  • api/db/services/canvas_service.py

Comment thread agent/component/llm.py Resolved
@jsdevninja
jsdevninja force-pushed the feat/agent-chat-template-kwargs-passthrough branch from 7bcdc0e to d836f62 Compare May 19, 2026 19:08
@jsdevninja
jsdevninja force-pushed the feat/agent-chat-template-kwargs-passthrough branch from d836f62 to 67b8cf7 Compare May 20, 2026 05:50

@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)
agent/canvas.py (1)

405-409: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Prevent stale sys.chat_template_kwargs from leaking across runs.

Current truthiness gating drops {} and leaves prior values in self.globals, so later requests can unintentionally reuse old template kwargs.

Proposed patch
-        for k in kwargs.keys():
-            if k in ["query", "user_id", "files", "chat_template_kwargs"] and kwargs[k]:
+        for k in kwargs.keys():
+            if k in ["query", "user_id", "files"] and kwargs[k]:
                 if k == "files":
                     self.globals[f"sys.{k}"] = await self.get_files_async(kwargs[k], layout_recognize)
                 else:
                     self.globals[f"sys.{k}"] = kwargs[k]
+        if "chat_template_kwargs" in kwargs:
+            self.globals["sys.chat_template_kwargs"] = kwargs["chat_template_kwargs"]
+        else:
+            self.globals.pop("sys.chat_template_kwargs", None)
♻️ Duplicate comments (1)
agent/component/llm.py (1)

451-454: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Handle missing sys.chat_template_kwargs without raising.

This still raises KeyError when the global is unset, which can break LLM execution on requests that don’t provide template kwargs.

Proposed patch
     def _get_chat_template_kwargs(self) -> dict[str, Any]:
-        chat_template_kwargs = self._canvas.get_variable_value("sys.chat_template_kwargs")
+        try:
+            chat_template_kwargs = self._canvas.get_variable_value("sys.chat_template_kwargs")
+        except KeyError:
+            return {}
         if chat_template_kwargs is None:
             return {}
🤖 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 451 - 454, The _get_chat_template_kwargs
method currently calls
self._canvas.get_variable_value("sys.chat_template_kwargs") but can raise
KeyError when the global is unset; change the method to handle that by wrapping
the get_variable_value call in a try/except KeyError (and return {} on KeyError)
so missing sys.chat_template_kwargs doesn't propagate an exception; keep the
existing None check and return {} for None as well—update the
_get_chat_template_kwargs implementation to catch the KeyError from
self._canvas.get_variable_value and return an empty dict.
🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)

217-225: ⚡ Quick win

Add non-sensitive logging for the new passthrough flow.

This new path should log whether chat_template_kwargs was forwarded (without logging payload contents).

Proposed patch
     run_kwargs = {
         "query": query,
         "files": files,
         "user_id": user_id,
         "inputs": inputs,
     }
     if chat_template_kwargs is not None:
         run_kwargs["chat_template_kwargs"] = chat_template_kwargs
+    logging.info(
+        "agent workflow run: agent_id=%s session_id=%s has_chat_template_kwargs=%s",
+        agent_id,
+        session_id,
+        chat_template_kwargs is not None,
+    )
As per coding guidelines "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 `@api/apps/restful_apis/agent_api.py` around lines 217 - 225, The new
passthrough flow doesn't log whether chat_template_kwargs was forwarded; update
the code around the run_kwargs construction so it emits a non-sensitive log
entry indicating only whether chat_template_kwargs was included (true/false)
without logging its contents. Specifically, after building run_kwargs and the
conditional that sets run_kwargs["chat_template_kwargs"], add a single
info/debug log using the existing logger (e.g., logger or process_logger) that
records something like "passthrough: forwarded_chat_template_kwargs=true/false"
referencing the run_kwargs and chat_template_kwargs symbols so reviewers can
find it, ensuring no payload or sensitive data is written to logs.
🤖 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.

Duplicate comments:
In `@agent/component/llm.py`:
- Around line 451-454: The _get_chat_template_kwargs method currently calls
self._canvas.get_variable_value("sys.chat_template_kwargs") but can raise
KeyError when the global is unset; change the method to handle that by wrapping
the get_variable_value call in a try/except KeyError (and return {} on KeyError)
so missing sys.chat_template_kwargs doesn't propagate an exception; keep the
existing None check and return {} for None as well—update the
_get_chat_template_kwargs implementation to catch the KeyError from
self._canvas.get_variable_value and return an empty dict.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 217-225: The new passthrough flow doesn't log whether
chat_template_kwargs was forwarded; update the code around the run_kwargs
construction so it emits a non-sensitive log entry indicating only whether
chat_template_kwargs was included (true/false) without logging its contents.
Specifically, after building run_kwargs and the conditional that sets
run_kwargs["chat_template_kwargs"], add a single info/debug log using the
existing logger (e.g., logger or process_logger) that records something like
"passthrough: forwarded_chat_template_kwargs=true/false" referencing the
run_kwargs and chat_template_kwargs symbols so reviewers can find it, ensuring
no payload or sensitive data is written to logs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 07f1fb7a-9d95-4f3d-9c01-c9a6bca3de70

📥 Commits

Reviewing files that changed from the base of the PR and between d836f62 and 67b8cf7.

📒 Files selected for processing (4)
  • agent/canvas.py
  • agent/component/llm.py
  • api/apps/restful_apis/agent_api.py
  • api/db/services/canvas_service.py

@jsdevninja

Copy link
Copy Markdown
Contributor Author

@Haruko386 Would you review please?

@KevinHuSh KevinHuSh added the ci Continue Integration label May 21, 2026
@jsdevninja
jsdevninja requested a review from KevinHuSh May 21, 2026 07:53
@jsdevninja
jsdevninja force-pushed the feat/agent-chat-template-kwargs-passthrough branch from 5f3449d to f5f6508 Compare May 21, 2026 09:32
@codecov

codecov Bot commented May 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (440153c) to head (05d2798).
⚠️ Report is 19 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14542   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Sentry.
📢 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.

@jsdevninja
jsdevninja force-pushed the feat/agent-chat-template-kwargs-passthrough branch from 09fce62 to 8bb828b Compare May 21, 2026 09:49
@jsdevninja
jsdevninja force-pushed the feat/agent-chat-template-kwargs-passthrough branch from 8bb828b to 05d2798 Compare May 21, 2026 10:39
@jsdevninja

Copy link
Copy Markdown
Contributor Author

@KevinHuSh Please review

@JinHai-CN
JinHai-CN merged commit 8f90740 into infiniflow:main May 22, 2026
1 check passed
wangq8 pushed a commit that referenced this pull request May 27, 2026
### What problem does this PR solve?

API reference updates based on #14542.

### Type of change


- [x] Documentation Update
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. size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Add the chat_template_kwargs parameter to the agent API to enable control over the thinking mode.

3 participants