Repository navigation
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughchat_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. ChangesChat template passthrough
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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 winAvoid 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_kwargsis 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 winAdd lightweight logging when forwarding
chat_template_kwargsin 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 winAdd debug logging for the new
chat_template_kwargsservice 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
📒 Files selected for processing (4)
agent/canvas.pyagent/component/llm.pyapi/apps/restful_apis/agent_api.pyapi/db/services/canvas_service.py
7bcdc0e to
d836f62
Compare
d836f62 to
67b8cf7
Compare
There was a problem hiding this comment.
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 winPrevent stale
sys.chat_template_kwargsfrom leaking across runs.Current truthiness gating drops
{}and leaves prior values inself.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 winHandle missing
sys.chat_template_kwargswithout raising.This still raises
KeyErrorwhen 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 winAdd non-sensitive logging for the new passthrough flow.
This new path should log whether
chat_template_kwargswas forwarded (without logging payload contents).As per coding guidelines "Add logging for new flows".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, + )🤖 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
📒 Files selected for processing (4)
agent/canvas.pyagent/component/llm.pyapi/apps/restful_apis/agent_api.pyapi/db/services/canvas_service.py
|
@Haruko386 Would you review please? |
5f3449d to
f5f6508
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
09fce62 to
8bb828b
Compare
8bb828b to
05d2798
Compare
|
@KevinHuSh Please review |
### What problem does this PR solve? API reference updates based on #14542. ### Type of change - [x] Documentation Update
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