Repository navigation
feat(nodes): add prompt template node with variable substitution - #894
Rod-Christensen wants to merge 8 commits into
Conversation
Add a new prompt_template node that renders prompt templates with dynamic
variable substitution. Features include:
- {{variable}} placeholder replacement from pipeline context
- Built-in helpers: {{now}}, {{uuid}}, {{random}}
- Conditional sections: {% if var %}...{% endif %}
- Loop support: {% for item in list %}...{% endfor %}
- Escape sequences for literal braces
- Zero external dependencies (stdlib only)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Remove unnecessary "gpu" capability from services.json - Fix _get_template_context to copy variables dict instead of mutating shared config - Re-raise exceptions in closing() instead of silently swallowing them - Fix _resolve to check context before falling back to built-in helpers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Prevents AttributeError when config is None during CONFIG mode or after endGlobal(). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Fix variables dict copy: validate type before calling dict() to avoid TypeError when config['variables'] is None - Defer question rendering to closing() so templates have access to all text collected via writeText(), fixing order-dependent rendering - Remove unrelated PageStatus.tsx and styles.css changes Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Restructure _resolve() so context is checked before builtins with clear separation and comments documenting the priority order - Add comprehensive test case validating actual template substitution Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Adds 57 unit tests covering the custom template engine (stdlib-only, no Jinja2) in nodes/test/test_prompt_template_engine.py — variable substitution, dotted paths, missing variables, builtins, context-over- builtin overrides, if/elif/else, nested blocks, for loops, escape sequences, malformed/unclosed tags, HTML pass-through, and ReDoS / recursion safety. The test module loads template_engine.py directly via importlib so it does not trigger the depends-based package init. Also addresses outstanding review feedback on PR #573: - Mark the node as experimental in services.json (per asclearuc) - Add an explicit {{question}} substitution test case in services.json (per CodeRabbit) - Add missing return type annotations on _resolve (Any), _at_top_level (bool), _handle_if (int) and _handle_for (int) to satisfy Ruff ANN202 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
📝 WalkthroughWalkthroughIntroduces a complete Prompt Template node for rocketride. A stdlib-only template engine handles variable substitution, conditionals, loops, and built-in helpers. Global lifecycle hooks manage configuration, instance handlers render templates from accumulated text/questions, and service definitions register the node with protocol, lanes, and test cases. ChangesPrompt Template Node Implementation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes 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. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsStopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a 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: 5
🤖 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 `@nodes/src/nodes/prompt_template/IGlobal.py`:
- Around line 28-44: Add PEP 257 docstrings to the IGlobal class and its
lifecycle methods: add a one-line docstring under class IGlobal describing its
role as the global lifecycle handler for prompt template nodes, and add concise
docstrings for beginGlobal and endGlobal describing when they are called (e.g.,
beginGlobal initializes per-node config and dependencies when OPEN_MODE.CONFIG
is not set; endGlobal clears the config) plus any important side-effects (calls
depends(), sets self.config). Keep them short, imperative where appropriate, and
place them immediately below the class and def lines for IGlobal, beginGlobal,
and endGlobal.
In `@nodes/src/nodes/prompt_template/IInstance.py`:
- Around line 31-65: Add PEP 257 docstrings to the public lifecycle class and
methods: document the IInstance class itself and its methods open,
writeQuestions, writeText, and closing with concise one-line summary plus a
short description of purpose/parameters/return where applicable (e.g.,
open(self, entry: Entry) should mention the Entry param, writeQuestions(self,
question: Question) should state it consumes Question and updates internal
state, writeText(self, text: str) should state it appends to collected_text, and
closing(self) should describe cleanup behavior); place the docstrings directly
under the class and each method signature to match repo docstring standards and
keep wording consistent with existing node docstrings.
In `@nodes/src/nodes/prompt_template/services.json`:
- Line 50: Replace the typo in the comment string "Description to of this
driver" with the correct wording "Description of this driver" so the comment
reads clearly; locate the exact commented text "Description to of this driver"
in services.json and update it to "Description of this driver".
- Line 33: Fix the typo in the JSON comment: change the word "pyhsical" to
"physical" in the comment that reads "The node is the actual pyhsical node to
instantiate" (search for that exact comment string in services.json to locate
it).
In `@nodes/test/prompt_template/test_engine.py`:
- Around line 59-65: The _ENGINE_PATH calculation in the test uses
.parent.parent which points to nodes/test/ and causes a FileNotFoundError when
exec_module runs; update the path resolution used when creating _ENGINE_PATH so
it climbs one directory higher (use three .parent calls instead of two) so the
path points to the package root where
src/nodes/prompt_template/template_engine.py actually lives; ensure the existing
spec creation (importlib.util.spec_from_file_location), module object
(template_engine), and exec_module usage remain unchanged.
🪄 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: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: f76833d9-8460-45c5-b3c8-47df0ee358d2
📒 Files selected for processing (7)
nodes/src/nodes/prompt_template/IGlobal.pynodes/src/nodes/prompt_template/IInstance.pynodes/src/nodes/prompt_template/__init__.pynodes/src/nodes/prompt_template/requirements.txtnodes/src/nodes/prompt_template/services.jsonnodes/src/nodes/prompt_template/template_engine.pynodes/test/prompt_template/test_engine.py
| class IGlobal(IGlobalBase): | ||
| config = None | ||
|
|
||
| def beginGlobal(self): | ||
| if self.IEndpoint.endpoint.openMode == OPEN_MODE.CONFIG: | ||
| pass | ||
| else: | ||
| import os | ||
| from depends import depends # type: ignore | ||
|
|
||
| requirements = os.path.dirname(os.path.realpath(__file__)) + '/requirements.txt' | ||
| depends(requirements) | ||
|
|
||
| self.config = Config.getNodeConfig(self.glb.logicalType, self.glb.connConfig) | ||
|
|
||
| def endGlobal(self): | ||
| self.config = None |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add PEP 257 docstrings to the class and lifecycle methods.
IGlobal, beginGlobal, and endGlobal are public lifecycle surfaces in nodes/**/*.py; add concise docstrings for guideline/lint compliance.
💡 Suggested patch
class IGlobal(IGlobalBase):
+ """Global lifecycle handler for the prompt_template node."""
config = None
def beginGlobal(self):
+ """Initialize dependencies and node configuration for runtime mode."""
if self.IEndpoint.endpoint.openMode == OPEN_MODE.CONFIG:
pass
else:
@@
self.config = Config.getNodeConfig(self.glb.logicalType, self.glb.connConfig)
def endGlobal(self):
+ """Release node-global state after execution."""
self.config = NoneAs per coding guidelines, nodes/**/*.py files must follow PEP 257 docstrings.
📝 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.
| class IGlobal(IGlobalBase): | |
| config = None | |
| def beginGlobal(self): | |
| if self.IEndpoint.endpoint.openMode == OPEN_MODE.CONFIG: | |
| pass | |
| else: | |
| import os | |
| from depends import depends # type: ignore | |
| requirements = os.path.dirname(os.path.realpath(__file__)) + '/requirements.txt' | |
| depends(requirements) | |
| self.config = Config.getNodeConfig(self.glb.logicalType, self.glb.connConfig) | |
| def endGlobal(self): | |
| self.config = None | |
| class IGlobal(IGlobalBase): | |
| """Global lifecycle handler for the prompt_template node.""" | |
| config = None | |
| def beginGlobal(self): | |
| """Initialize dependencies and node configuration for runtime mode.""" | |
| if self.IEndpoint.endpoint.openMode == OPEN_MODE.CONFIG: | |
| pass | |
| else: | |
| import os | |
| from depends import depends # type: ignore | |
| requirements = os.path.dirname(os.path.realpath(__file__)) + '/requirements.txt' | |
| depends(requirements) | |
| self.config = Config.getNodeConfig(self.glb.logicalType, self.glb.connConfig) | |
| def endGlobal(self): | |
| """Release node-global state after execution.""" | |
| self.config = 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 `@nodes/src/nodes/prompt_template/IGlobal.py` around lines 28 - 44, Add PEP 257
docstrings to the IGlobal class and its lifecycle methods: add a one-line
docstring under class IGlobal describing its role as the global lifecycle
handler for prompt template nodes, and add concise docstrings for beginGlobal
and endGlobal describing when they are called (e.g., beginGlobal initializes
per-node config and dependencies when OPEN_MODE.CONFIG is not set; endGlobal
clears the config) plus any important side-effects (calls depends(), sets
self.config). Keep them short, imperative where appropriate, and place them
immediately below the class and def lines for IGlobal, beginGlobal, and
endGlobal.
| class IInstance(IInstanceBase): | ||
| IGlobal: IGlobal | ||
|
|
||
| def __init__(self): | ||
| """Initialize the prompt template node instance state.""" | ||
| super().__init__() | ||
| self.collected_text: list[str] = [] | ||
| self.question = Question() | ||
|
|
||
| def open(self, entry: Entry): | ||
| pass | ||
|
|
||
| def _get_template_context(self) -> dict: | ||
| """Build the context dictionary for template rendering.""" | ||
| config = self.IGlobal.config | ||
| if config is None: | ||
| config = {} | ||
| raw_variables = config.get('variables', {}) | ||
| variables = dict(raw_variables) if isinstance(raw_variables, dict) else {} | ||
|
|
||
| # Add collected text as 'input' if available | ||
| if self.collected_text: | ||
| variables.setdefault('input', '\n'.join(self.collected_text)) | ||
|
|
||
| return variables | ||
|
|
||
| def writeQuestions(self, question: Question): | ||
| for q in question.questions: | ||
| self.question.addQuestion(q.text) | ||
|
|
||
| def writeText(self, text: str): | ||
| self.collected_text.append(text) | ||
|
|
||
| def closing(self): | ||
| try: |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Document public instance lifecycle methods with PEP 257 docstrings.
Please add docstrings for IInstance, open, writeQuestions, writeText, and closing to keep this node aligned with repo docstring standards.
As per coding guidelines, nodes/**/*.py files must include PEP 257 docstrings.
🤖 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 `@nodes/src/nodes/prompt_template/IInstance.py` around lines 31 - 65, Add PEP
257 docstrings to the public lifecycle class and methods: document the IInstance
class itself and its methods open, writeQuestions, writeText, and closing with
concise one-line summary plus a short description of purpose/parameters/return
where applicable (e.g., open(self, entry: Entry) should mention the Entry param,
writeQuestions(self, question: Question) should state it consumes Question and
updates internal state, writeText(self, text: str) should state it appends to
collected_text, and closing(self) should describe cleanup behavior); place the
docstrings directly under the class and each method signature to match repo
docstring standards and keep wording consistent with existing node docstrings.
| "register": "filter", | ||
| // | ||
| // Optional: | ||
| // The node is the actual pyhsical node to instantiate - if |
There was a problem hiding this comment.
Fix typo in comment.
"pyhsical" should be "physical".
📝 Proposed fix
- // The node is the actual pyhsical node to instantiate - if
+ // The node is the actual physical node to instantiate - if📝 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.
| // The node is the actual pyhsical node to instantiate - if | |
| // The node is the actual physical node to instantiate - if |
🤖 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 `@nodes/src/nodes/prompt_template/services.json` at line 33, Fix the typo in
the JSON comment: change the word "pyhsical" to "physical" in the comment that
reads "The node is the actual pyhsical node to instantiate" (search for that
exact comment string in services.json to locate it).
| "prefix": "prompt_template", | ||
| // | ||
| // Optional: | ||
| // Description to of this driver |
There was a problem hiding this comment.
Fix typo in comment.
"Description to of" should be "Description of".
📝 Proposed fix
- // Description to of this driver
+ // Description of this driver📝 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.
| // Description to of this driver | |
| // Description of this driver |
🤖 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 `@nodes/src/nodes/prompt_template/services.json` at line 50, Replace the typo
in the comment string "Description to of this driver" with the correct wording
"Description of this driver" so the comment reads clearly; locate the exact
commented text "Description to of this driver" in services.json and update it to
"Description of this driver".
| _ENGINE_PATH = Path(__file__).resolve().parent.parent / 'src' / 'nodes' / 'prompt_template' / 'template_engine.py' | ||
|
|
||
| _spec = importlib.util.spec_from_file_location('prompt_template_engine', _ENGINE_PATH) | ||
| assert _spec is not None and _spec.loader is not None, 'failed to locate template_engine.py' | ||
| template_engine = importlib.util.module_from_spec(_spec) | ||
| sys.modules['prompt_template_engine'] = template_engine | ||
| _spec.loader.exec_module(template_engine) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- engine location(s) ---'
fd -t f 'template_engine.py'
echo
echo '--- test file location(s) ---'
fd -t f 'test_engine.py' --full-path -E '*/node_modules/*'
echo
echo '--- resolve both and compute the relative depth ---'
python3 - <<'PY'
from pathlib import Path
import subprocess
def first(cmd):
out = subprocess.check_output(cmd, text=True).strip().splitlines()
return out[0] if out else None
engine = first(['fd', '-t', 'f', 'template_engine.py'])
test_ = first(['fd', '-t', 'f', 'test_engine.py'])
print('engine:', engine)
print('test :', test_)
if engine and test_:
t = Path(test_).resolve()
print('test.parent :', t.parent)
print('test.parent.parent:', t.parent.parent)
print('test.parent.parent.parent:', t.parent.parent.parent)
candidate_2p = t.parent.parent / 'src' / 'nodes' / 'prompt_template' / 'template_engine.py'
candidate_3p = t.parent.parent.parent / 'src' / 'nodes' / 'prompt_template' / 'template_engine.py'
print('exists with 2 parents:', candidate_2p.exists(), '->', candidate_2p)
print('exists with 3 parents:', candidate_3p.exists(), '->', candidate_3p)
PYRepository: rocketride-org/rocketride-server
Length of output: 765
Fix off-by-one path error in engine module import — code will fail at runtime with FileNotFoundError.
The test file at nodes/test/prompt_template/test_engine.py uses .parent.parent to resolve the engine path, which lands at nodes/test/. Joining src/nodes/prompt_template/template_engine.py to this directory produces nodes/test/src/nodes/prompt_template/template_engine.py, which does not exist. The actual engine resides at nodes/src/nodes/prompt_template/template_engine.py, requiring three .parent calls from the test file to reach the nodes/ package root. The importlib.util.spec_from_file_location call succeeds even with a non-existent path, so the assertion passes; the failure surfaces only at _spec.loader.exec_module(template_engine) (line 65), breaking the test suite at collection time.
Fix: use three `.parent` calls
-_ENGINE_PATH = Path(__file__).resolve().parent.parent / 'src' / 'nodes' / 'prompt_template' / 'template_engine.py'
+_ENGINE_PATH = (
+ Path(__file__).resolve().parent.parent.parent
+ / 'src'
+ / 'nodes'
+ / 'prompt_template'
+ / 'template_engine.py'
+)
+assert _ENGINE_PATH.is_file(), f'template_engine.py not found at {_ENGINE_PATH}'🤖 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 `@nodes/test/prompt_template/test_engine.py` around lines 59 - 65, The
_ENGINE_PATH calculation in the test uses .parent.parent which points to
nodes/test/ and causes a FileNotFoundError when exec_module runs; update the
path resolution used when creating _ENGINE_PATH so it climbs one directory
higher (use three .parent calls instead of two) so the path points to the
package root where src/nodes/prompt_template/template_engine.py actually lives;
ensure the existing spec creation (importlib.util.spec_from_file_location),
module object (template_engine), and exec_module usage remain unchanged.
|
Hi @Rod-Christensen — the prompt-template node looks good. Heads-up that CI is red (Build failing on Ubuntu/macOS/Windows + |
|
I checked whether this landed some other way while the PR sat: it did not. There is still no template node under Three things stand between it and a review:
|
🤖 Internal: Discord sync markerAuto-managed by the Discord notification workflow. Stores the linked Discord message ID and forum thread ID. Do not edit or delete. |
Summary
Adds a new
prompt_templatepipeline node that renders prompt templates with dynamic variable substitution from pipeline context.{{variable}}placeholders resolved from pipeline context{{now}},{{uuid}},{{random}}{% if %}/{% elif %}/{% else %}/{% endif %}{% for item in list %}/{% endfor %}\{{for literal bracesRebased from #573 (by @charliegillet). Original authorship preserved in commits.
Test plan
{{variable}}substitution renders correctly🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
if/elif/else), and loopsnow(ISO8601 UTC),uuid(UUIDv4),random(0-1)Tests