Skip to content

Conversation

@wazmaaali
Copy link

@wazmaaali wazmaaali commented Aug 7, 2025

Description

Brief description of what this PR does.

Changes Made

-Changes Made
Added runway_text2img.py under custom_nodes/
Created a node that sends a POST request to Runway's /v1/text_to_image endpoint
Integrated node to accept prompt from upstream (e.g., CLIPTextEncode)
Implemented environment variable check for RUNWAY_API_KEY
Added docstring for usage, parameters, defaults, and timeout config
Ensured compatibility with ComfyUI node system
Handled missing API key with a clear error message
CI test file tests/api_nodes/test_runway_text2img.py passes (with mocked HTTP requests)

Evidence Required ✅

UI Screenshot

UI Screenshot

Generated Image

Generated Image

Logs

# Paste logs here

Tests (Optional)

platform darwin -- Python 3.11.8, pytest-8.0.0
collected 1 item

tests/api_nodes/test_runway_text2img.py .

Checklist

  • [ Yes] UI screenshot provided
  • Generated image provided
  • Logs provided
  • [ Yes] Tests added (optional)
  • [Yes ] Code follows project style
  • [ Yes] Self-review completed

Summary by Sourcery

Add a Runway Gen-4 text-to-image ComfyUI node that retrieves the API key from the environment, handles missing keys gracefully, and includes unit tests with mocked HTTP requests.

New Features:

  • Add RunwayText2Image node to send prompts to Runway Gen-4 text-to-image API within ComfyUI
  • Integrate prompt input from upstream nodes and support configurable poll timeout
  • Load RUNWAY_API_KEY from environment variable and surface a clear error if missing

Enhancements:

  • Provide docstring detailing usage, parameters, defaults, and timeout configuration

Tests:

  • Add unit tests with mocked HTTP requests for successful image generation
  • Add unit test to verify error is raised when RUNWAY_API_KEY is not set

Summary by CodeRabbit

  • New Features
    • Added a new node that generates images from text prompts using the Runway API, with configurable timeout settings.
  • Tests
    • Introduced unit tests to verify successful image generation and proper error handling when the API key is missing.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 7, 2025

Walkthrough

A new node class RunwayText2Image was added to generate images via Runway's text-to-image API using a prompt and a timeout parameter. Corresponding unit tests were introduced, covering successful image generation with mocked HTTP requests and handling the missing API key error. A pytest fixture for dummy image bytes was also included.

Changes

Cohort / File(s) Change Summary
RunwayText2Image Node Implementation
ComfyUI/custom_nodes/runway_text2img.py
Added RunwayText2Image node class that calls Runway's text-to-image API, handles authentication, downloads and returns the generated image. Registered the node in mappings.
RunwayText2Image Unit Tests
ComfyUI/tests/api_nodes/test_runway_text2img.py
Added unit tests for RunwayText2Image: one tests successful image generation with mocked environment and HTTP requests; another tests error on missing API key. Added a fixture for dummy image bytes.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Function
    participant Env as Environment (API Key)
    participant HTTP as HTTP (POST/GET)
    participant Node as RunwayText2Image

    Test->>Env: Mock API Key
    Test->>HTTP: Mock POST (image generation request)
    HTTP-->>Test: Return image URL
    Test->>HTTP: Mock GET (download image)
    HTTP-->>Test: Return dummy image bytes
    Test->>Node: Call generate_image(prompt)
    Node-->>Test: Return PIL Image
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Poem

A bunny in code, with tests to arrange,
Mocks up the world, so nothing feels strange.
Images created, with bytes black as night,
API keys missing? It catches that plight!
With fixtures and mocks, the tests hop along—
In the garden of Python, all bugs are gone. 🐇

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3c321f8 and 544da71.

📒 Files selected for processing (1)
  • ComfyUI/tests/api_nodes/test_runway_text2img.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ComfyUI/tests/api_nodes/test_runway_text2img.py
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Aug 7, 2025

Reviewer's Guide

This PR adds a new ComfyUI node, RunwayText2Image, to interface with the Runway Gen-4 text-to-image API by sending HTTP requests, handling environment-based authentication, and returning PIL Image outputs, along with corresponding unit tests.

File-Level Changes

Change Details Files
Introduce RunwayText2Image node for ComfyUI to call Runway Gen-4 text-to-image API
  • Defined RunwayText2Image class that accepts prompt input and outputs a PIL Image
  • Implemented generate_image method to read RUNWAY_API_KEY, send POST to /v1/text_to_image, poll and download the generated image
  • Added clear error handling for missing API key and configurable timeout
  • Documented usage, parameters, defaults, and timeout in the node’s docstring
custom_nodes/runway_text2img.py
Add unit tests for RunwayText2Image node with mocked HTTP interactions
  • Created fixture for dummy image bytes representing a 1×1 PNG
  • Mocked os.getenv, requests.post, and requests.get to simulate API key retrieval, successful generation, and image download
  • Verified correct PIL Image output and size in success scenario
  • Tested raising RuntimeError when RUNWAY_API_KEY is missing
ComfyUI/tests/api_nodes/test_runway_text2img.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @wazmaaali - I've reviewed your changes - here's some feedback:

  • Consider exposing key API parameters like width, height, and steps as node inputs so users can customize the output resolution and quality directly in the UI.
  • Enhance error handling by capturing non-200 responses and including the status code and error message in the raised exception to help users diagnose API issues faster.
  • Implement retry/backoff logic for transient network failures or rate limiting (e.g., 429 responses) to make the node more robust under unreliable network conditions.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider exposing key API parameters like width, height, and steps as node inputs so users can customize the output resolution and quality directly in the UI.
- Enhance error handling by capturing non-200 responses and including the status code and error message in the raised exception to help users diagnose API issues faster.
- Implement retry/backoff logic for transient network failures or rate limiting (e.g., 429 responses) to make the node more robust under unreliable network conditions.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@wazmaaali
Copy link
Author

Added runway_text2img node for DreamLayer open-source challenge (Task #1).
This node integrates with the Runway Gen-4 API, plugs into a prompt-based ComfyUI grap.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
ComfyUI/tests/api_nodes/test_runway_text2img.py (1)

15-38: Comprehensive test with minor improvement opportunities.

The test effectively covers the success scenario with proper mocking. Consider these enhancements:

-    mock_post.return_value.json.return_value = {"image_url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTwBchNsxAEthMtT_uv1MInGKEi4A0W2b1mx1flcpNOoUMkiy0CCnLfKF55jqIiRB9Mx-Y&usqp=CAU"}
+    mock_post.return_value.json.return_value = {"image_url": "https://example.com/test-image.png"}

Additionally, consider adding assertions to verify the API calls:

# Verify POST was called with correct parameters
mock_post.assert_called_once()
# Verify GET was called to download the image
mock_get.assert_called_once_with("https://example.com/test-image.png")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e628e6 and 3d2d7d6.

📒 Files selected for processing (1)
  • ComfyUI/tests/api_nodes/test_runway_text2img.py (1 hunks)
🔇 Additional comments (3)
ComfyUI/tests/api_nodes/test_runway_text2img.py (3)

1-5: LGTM! Clean import structure.

The imports are well-organized and include all necessary dependencies for comprehensive testing with proper mocking capabilities.


7-13: LGTM! Well-implemented test fixture.

The fixture efficiently creates minimal test data and properly returns PNG bytes that can be used to mock HTTP responses. The implementation is clean and well-documented.


40-46: LGTM! Solid error handling test.

The test properly validates the missing API key scenario using pytest.raises with message matching. This ensures robust error handling and clear error messages for users.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
ComfyUI/custom_nodes/runway_text2img.py (1)

12-36: Excellent documentation, but reconsider inheritance choice.

The docstring is comprehensive and well-structured, clearly explaining usage, parameters, and requirements.

However, inheriting from CLIPTextEncode may not be semantically correct since this node generates images rather than encoding text. Consider inheriting from a more appropriate base class or directly from the ComfyUI node base class.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d2d7d6 and 3c321f8.

📒 Files selected for processing (1)
  • ComfyUI/custom_nodes/runway_text2img.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.12.2)
ComfyUI/custom_nodes/runway_text2img.py

6-6: Redefinition of unused os from line 1

Remove definition: os

(F811)

🔇 Additional comments (2)
ComfyUI/custom_nodes/runway_text2img.py (2)

38-45: LGTM!

The INPUT_TYPES method follows ComfyUI conventions correctly with appropriate parameter types, defaults, and constraints.


78-84: LGTM!

Node mappings follow ComfyUI conventions correctly with appropriate class registration and user-friendly display names.

Comment on lines +1 to +7
import os
import requests
from io import BytesIO
from PIL import Image
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix duplicate import and simplify path handling.

The os module is imported twice (lines 1 and 6), and the sys.path manipulation is unnecessarily complex.

Apply this diff to fix the duplicate import:

 import os
 import requests
 from io import BytesIO
 from PIL import Image
 import sys
-import os
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))

Consider whether the sys.path manipulation is necessary - using relative imports or proper package structure might be cleaner.

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

Suggested change
import os
import requests
from io import BytesIO
from PIL import Image
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
import os
import requests
from io import BytesIO
from PIL import Image
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
🧰 Tools
🪛 Ruff (0.12.2)

6-6: Redefinition of unused os from line 1

Remove definition: os

(F811)

🤖 Prompt for AI Agents
In ComfyUI/custom_nodes/runway_text2img.py lines 1 to 7, remove the duplicate
import of the os module and simplify the sys.path insertion by using a clearer,
more straightforward path expression. Also, evaluate if modifying sys.path is
necessary at all; if possible, replace it with relative imports or adjust the
package structure to avoid this manipulation.

Comment on lines +50 to +77
def generate_image(self, prompt, poll_timeout):
api_key = os.getenv("RUNWAY_API_KEY")
if not api_key:
raise RuntimeError("Missing environment variable: RUNWAY_API_KEY")

headers = {"Authorization": f"Bearer {api_key}"}
payload = {"prompt": prompt}

try:
response = requests.post(
"https://api.dev.runwayml.com/v1/text_to_image",
json=payload,
headers=headers,
timeout=poll_timeout
)
response.raise_for_status()
image_url = response.json().get("image_url")
if not image_url:
raise ValueError("No image URL returned from Runway API")

image_data = requests.get(image_url).content
image = Image.open(BytesIO(image_data)).convert("RGB")

return (image,)

except Exception as e:
raise RuntimeError(f"RunwayText2Image generation failed: {e}")

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add timeout and error handling for image download.

The image download request (line 70) lacks timeout and error handling, which could cause the node to hang indefinitely or fail silently.

Apply this diff to improve error handling:

             image_url = response.json().get("image_url")
             if not image_url:
                 raise ValueError("No image URL returned from Runway API")
 
-            image_data = requests.get(image_url).content
+            image_response = requests.get(image_url, timeout=30)
+            image_response.raise_for_status()
+            image_data = image_response.content
             image = Image.open(BytesIO(image_data)).convert("RGB")

Additionally, consider more specific exception handling instead of catching all exceptions on line 75.

🤖 Prompt for AI Agents
In ComfyUI/custom_nodes/runway_text2img.py lines 50 to 77, the image download
request lacks a timeout and error handling, which can cause hangs or silent
failures. Add a timeout parameter to the requests.get call for image_data and
wrap it in a try-except block to catch request exceptions specifically. Also,
replace the broad except Exception on line 75 with more specific exceptions like
requests.RequestException and handle them accordingly to improve error clarity
and robustness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant