Repository navigation
Fix: variable in doc generator - #14180
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughTemplate/variable resolution was refactored: Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Client
participant Invoke
participant Canvas
participant HTTP as "External API"
participant Parser as "HtmlParser"
Client->>Invoke: call _invoke(kwargs)
Invoke->>Canvas: _resolve_variable_value / get_variable_value
Canvas-->>Invoke: variable values (str, None, partial, error)
Invoke->>Invoke: _render_template / _resolve_template_text (values, headers, url)
Invoke->>HTTP: _send_request(url, args, headers, proxies)
HTTP-->>Invoke: response
alt html_cleaning_enabled
Invoke->>Parser: _format_response -> clean HTML
Parser-->>Invoke: cleaned text
end
Invoke-->>Client: formatted response or error
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/docs_generator.py`:
- Around line 152-174: Repeated placeholder refs are re-resolved each time
inside the _replace_variable callback which can re-consume partial producers and
slow or make output inconsistent; add a local cache dict in docs_generator.py
used by _replace_variable (keyed by the match group string) to store the
resolved string/value so that on subsequent matches you return the cached result
instead of calling self._canvas.get_variable_value again; ensure you still
handle None, partial (consume it once and cache the resulting string), call
self._stringify_message_value for non-partial values, and preserve the existing
exception handling and fallback behavior.
- Around line 149-150: The runtime `content` value is being pulled with a
truthiness chain (self._param.content or kwargs.get("content", "") or "") which
drops valid falsy values (0/False) and leaves non-string types unnormalized
before calls to len(...) and re.sub(...); change the logic that sets `content`
so you first determine presence (e.g. check `"content" in kwargs` or `is not
None` for self._param.content) and then coerce the chosen value to a string
(e.g. use str(value) or "" for None) so `content` is always a string before the
logging call (logging.info(..., len(content))) and subsequent processing in this
module (references: variable `content`, attributes `self._param.content`,
kwargs.get("content"), and the logging.info call).
🪄 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: 57d3ea87-6fec-43c5-acbc-601ccb3c1965
📒 Files selected for processing (1)
agent/component/docs_generator.py
| content = self._param.content or kwargs.get("content", "") or "" | ||
| logging.info("Starting document generation, content length: %s chars", len(content)) |
There was a problem hiding this comment.
Normalize runtime content before treating it as a string.
Line 149 now pulls kwargs["content"] through a truthiness chain, which silently drops valid values like 0/False and passes non-string payloads straight into Line 150/169. That means upstream list/dict/partial content can now either disappear or fail during len(...) / re.sub(...) instead of being rendered.
Possible fix
- content = self._param.content or kwargs.get("content", "") or ""
+ raw_content = self._param.content if self._param.content != "" else kwargs.get("content", "")
+ if isinstance(raw_content, partial):
+ content = "".join(raw_content())
+ else:
+ content = self._stringify_message_value(raw_content, fallback_to_str=True)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@agent/component/docs_generator.py` around lines 149 - 150, The runtime
`content` value is being pulled with a truthiness chain (self._param.content or
kwargs.get("content", "") or "") which drops valid falsy values (0/False) and
leaves non-string types unnormalized before calls to len(...) and re.sub(...);
change the logic that sets `content` so you first determine presence (e.g. check
`"content" in kwargs` or `is not None` for self._param.content) and then coerce
the chosen value to a string (e.g. use str(value) or "" for None) so `content`
is always a string before the logging call (logging.info(..., len(content))) and
subsequent processing in this module (references: variable `content`, attributes
`self._param.content`, kwargs.get("content"), and the logging.info call).
| if content: | ||
| def _replace_variable(match_obj: re.Match[str]) -> str: | ||
| match = match_obj.group(1) | ||
| try: | ||
| var_value = self._canvas.get_variable_value(match) | ||
| if var_value is None: | ||
| continue | ||
| return "" | ||
| if isinstance(var_value, partial): | ||
| resolved_content = "" | ||
| for chunk in var_value(): | ||
| resolved_content += chunk | ||
| content = content.replace("{" + match + "}", resolved_content) | ||
| else: | ||
| content = content.replace("{" + match + "}", str(var_value)) | ||
| return resolved_content | ||
| return self._stringify_message_value(var_value, fallback_to_str=True) | ||
| except Exception as e: | ||
| logging.warning("Error resolving variable %s: %s", match, str(e)) | ||
| content = content.replace("{" + match + "}", f"[ERROR: {str(e)}]") | ||
| return f"[ERROR: {str(e)}]" | ||
|
|
||
| if content: | ||
| try: | ||
| content, _ = self.get_kwargs(content, kwargs) | ||
| except Exception as e: | ||
| logging.warning("Error processing content with get_kwargs: %s", str(e)) | ||
|
|
||
| if not content: | ||
| content = kwargs.get("content", "") | ||
| content = re.sub( | ||
| self.variable_ref_patt, | ||
| _replace_variable, | ||
| content, | ||
| flags=re.DOTALL, | ||
| ) |
There was a problem hiding this comment.
Cache repeated placeholder resolutions.
This re.sub callback resolves the same placeholder every time it appears, so repeated refs like {foo@bar} will hit self._canvas.get_variable_value(...) multiple times and can re-consume partial producers multiple times. Message._stream already caches by variable name, and without that here the same document can become slower or inconsistent when a ref is repeated.
Possible fix
if content:
+ cache: dict[str, str] = {}
+
def _replace_variable(match_obj: re.Match[str]) -> str:
match = match_obj.group(1)
+ if match in cache:
+ return cache[match]
try:
var_value = self._canvas.get_variable_value(match)
if var_value is None:
- return ""
+ cache[match] = ""
+ return ""
if isinstance(var_value, partial):
resolved_content = ""
for chunk in var_value():
resolved_content += chunk
+ cache[match] = resolved_content
return resolved_content
- return self._stringify_message_value(var_value, fallback_to_str=True)
+ resolved = self._stringify_message_value(var_value, fallback_to_str=True)
+ cache[match] = resolved
+ return resolved
except Exception as e:
logging.warning("Error resolving variable %s: %s", match, str(e))
return f"[ERROR: {str(e)}]"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@agent/component/docs_generator.py` around lines 152 - 174, Repeated
placeholder refs are re-resolved each time inside the _replace_variable callback
which can re-consume partial producers and slow or make output inconsistent; add
a local cache dict in docs_generator.py used by _replace_variable (keyed by the
match group string) to store the resolved string/value so that on subsequent
matches you return the cached result instead of calling
self._canvas.get_variable_value again; ensure you still handle None, partial
(consume it once and cache the resulting string), call
self._stringify_message_value for non-partial values, and preserve the existing
exception handling and fallback behavior.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14180 +/- ##
=======================================
Coverage 96.66% 96.66%
=======================================
Files 10 10
Lines 690 690
Branches 108 108
=======================================
Hits 667 667
Misses 8 8
Partials 15 15 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
agent/component/invoke.py (1)
127-127: Minor inconsistency:str(value)vs_stringify_message_value.The
docs_generator.pyimplementation usesself._stringify_message_value(var_value, fallback_to_str=True)which may handle complex types (lists, dicts) differently thanstr(value). For HTTP request contexts this may be acceptable, but consider whether consistent behavior across components is desired.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@agent/component/invoke.py` at line 127, The current return uses plain str(value) which is inconsistent with docs_generator.py and may handle complex types differently; replace the direct str(value) in agent/component/invoke.py with a call to the existing helper self._stringify_message_value(value, fallback_to_str=True) (or ensure you use that helper from the same class/module) so serialization of lists/dicts and other complex types matches docs_generator.py's behavior.
🤖 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/invoke.py`:
- Line 118: The code uses kwargs.get(match,
self._canvas.get_variable_value(match)) which evaluates get_variable_value()
even when match is present in kwargs, causing exceptions; change the logic to
check membership first (e.g., if match in kwargs: value = kwargs[match] else:
value = self._canvas.get_variable_value(match)) or retrieve with
kwargs.get(match) and call _canvas.get_variable_value(match) only when that
result is None, updating the assignment around the value variable accordingly.
---
Nitpick comments:
In `@agent/component/invoke.py`:
- Line 127: The current return uses plain str(value) which is inconsistent with
docs_generator.py and may handle complex types differently; replace the direct
str(value) in agent/component/invoke.py with a call to the existing helper
self._stringify_message_value(value, fallback_to_str=True) (or ensure you use
that helper from the same class/module) so serialization of lists/dicts and
other complex types matches docs_generator.py's behavior.
🪄 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: d2e25f94-05a8-4dbc-9f60-324026a4125b
📒 Files selected for processing (1)
agent/component/invoke.py
| def replace_variable(match_obj): | ||
| match = match_obj.group(1) | ||
| try: | ||
| value = kwargs.get(match, self._canvas.get_variable_value(match)) |
There was a problem hiding this comment.
Bug: kwargs.get() with exception-raising default causes incorrect behavior.
Python evaluates the default argument before dict.get() checks if the key exists. Since get_variable_value raises an exception when a component is not found (see agent/canvas.py:201), this will raise an exception even when match is present in kwargs, causing the exception handler to return [ERROR: ...] instead of the actual kwargs value.
🐛 Proposed fix
- value = kwargs.get(match, self._canvas.get_variable_value(match))
+ if match in kwargs:
+ value = kwargs[match]
+ else:
+ value = self._canvas.get_variable_value(match)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| value = kwargs.get(match, self._canvas.get_variable_value(match)) | |
| if match in kwargs: | |
| value = kwargs[match] | |
| else: | |
| value = self._canvas.get_variable_value(match) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@agent/component/invoke.py` at line 118, The code uses kwargs.get(match,
self._canvas.get_variable_value(match)) which evaluates get_variable_value()
even when match is present in kwargs, causing exceptions; change the logic to
check membership first (e.g., if match in kwargs: value = kwargs[match] else:
value = self._canvas.get_variable_value(match)) or retrieve with
kwargs.get(match) and call _canvas.get_variable_value(match) only when that
result is None, updating the assignment around the value variable accordingly.
### What problem does this PR solve? Fix: variable in doc generator ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
What problem does this PR solve?
Fix: variable in doc generator
Type of change