Building ComfyUI custom nodes for a remote generation API: polling, tensors, VIDEO outputs and keeping keys out of workflows
ComfyUI is usually about running models on your own GPU, but a growing number of node packs call remote APIs instead: the graph stays local, the heavy lifting happens on someone else's hardware.
I recently wrote one of these, comfyui-vellria, which wraps Vellria, a hosted image and video generation API (vellria.com). It is MIT licensed and small (five short Python modules), so it makes a decent case study.
This post walks through the parts that took the most thought. None of it is specific to one API; if you are wrapping any job-based HTTP service in ComfyUI nodes, the same problems show up.
The shape of a ComfyUI custom node pack
ComfyUI scans ComfyUI/custom_nodes/, imports each folder as a Python package, and reads two dictionaries from its __init__.py:
NODE_CLASS_MAPPINGS = {
"VellriaAPIKey": VellriaAPIKey,
"VellriaImage": VellriaImage,
"VellriaVideo": VellriaVideo,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"VellriaAPIKey": "Vellria API Key",
"VellriaImage": "Vellria Image",
"VellriaVideo": "Vellria Video",
}
Each node is a plain class. INPUT_TYPES returns the widgets and sockets, RETURN_TYPES names the outputs, and FUNCTION names the method ComfyUI calls. I used this classic interface rather than the newer schema-based one because current ComfyUI still loads it and older installs keep working.
One detail worth copying: ComfyUI-only imports (comfy.model_management, folder_paths, comfy_api) are wrapped in try/except, so the module imports cleanly under plain pytest without a ComfyUI checkout.
The root __init__.py also checks __package__, because pytest collecting the repo root imports it as a bare module:
if __package__:
# loaded by ComfyUI as a package
from .vellria_comfy.nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
...
else:
# imported as a plain module (e.g. by pytest collecting the repo root)
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
A dynamic model list that never breaks startup
The model dropdown is a combo widget, and combos are built when ComfyUI calls INPUT_TYPES, which happens once at load. So the model list has to be known at import time.
The pack fetches the public GET /v1/models endpoint with a 5 second timeout and falls back in order: live list, then a cached copy from the last successful run, then a snapshot bundled with the package.
if client is not None:
try:
data = client.list_models(timeout=min(timeout, 5.0))
if _valid(data):
_write_cache(data, cache_path)
return {"image": data["image"], "video": data["video"]}, "live"
except Exception as exc: # network, JSON, anything: fall back quietly
log.warning("Vellria: could not fetch the model list (%s); using a local list", exc)
cached = _read(cache_path)
if cached is not None:
return cached, "cache"
The rule I held to: a custom node must never take down ComfyUI startup. A user with no network, or behind a proxy, still gets working nodes with a slightly older list. The catalog request carries no API key at all, since it is public.
The catalog also describes each model's sizes, durations and optional parameters. The node uses that to validate the request locally: if a model doesn't offer a given aspect ratio at a given resolution, the node stops with a list of what it does offer, before anything is uploaded or billed.
Submitting a job and polling it properly
Image and video generation on the API is asynchronous. POST /v1/generate/image returns 202 with an id, and the client polls GET /v1/generations/{id} until the status is completed or failed.
Two things matter here: not hammering the server, and letting the user cancel. The poll interval starts at 2 seconds and grows by 1.25x per round up to 8 seconds. Transient errors (network failures, 5xx, 429) are tolerated up to five in a row; anything else is raised immediately.
POLL_INITIAL_S = 2.0
POLL_FACTOR = 1.25
POLL_MAX_S = 8.0
POLL_MAX_CONSECUTIVE_ERRORS = 5
try:
row = self.get_generation(generation_id)
errors = 0
except VellriaAPIError as exc:
transient = exc.status is None or exc.status >= 500 or exc.status == 429
errors += 1
if not transient or errors >= POLL_MAX_CONSECUTIVE_ERRORS:
raise
row = None
Cancellation is the part people often miss. When you click "Cancel" in the ComfyUI queue, nothing kills your Python thread. ComfyUI sets a flag, and your node has to check it by calling comfy.model_management.throw_exception_if_processing_interrupted().
A node that does time.sleep(8) in a loop ignores Cancel for up to 8 seconds per round, and a node that never checks waits until the job finishes. So the sleep is chopped into 0.25 second slices with a check after each:
def _interruptible_sleep(seconds, sleep, check):
step = 0.25
remaining = seconds
while remaining > 0:
chunk = min(step, remaining)
sleep(chunk)
remaining -= chunk
if check:
check()
sleep and clock are injected parameters of wait_for_generation, which makes the polling loop testable without real waiting. The tests feed a fake clock and assert on the backoff sequence and timeout behaviour.
The node also checks for cancellation once between uploading reference images and submitting the job, so a cancel during upload stops before anything is charged. A job that was already submitted keeps running on the server; the error message says so honestly instead of pretending it was aborted.
IMAGE tensors in, PNG bytes out (and back)
ComfyUI's IMAGE type is a float32 torch tensor shaped [batch, height, width, channels], values in 0..1, three channels. An HTTP API wants encoded files. The conversion is short but has a few edges:
def frame_to_png(frame) -> bytes:
if hasattr(frame, "detach"):
frame = frame.detach().cpu().numpy()
arr = np.clip(np.asarray(frame, dtype=np.float32) * 255.0 + 0.5, 0, 255).astype(np.uint8)
if arr.ndim == 2:
arr = arr[..., None]
if arr.shape[-1] == 1:
arr = np.repeat(arr, 3, axis=-1)
elif arr.shape[-1] == 4:
arr = arr[..., :3] # the API rejects transparent references
buf = io.BytesIO()
Image.fromarray(arr, "RGB").save(buf, format="PNG")
return buf.getvalue()
The + 0.5 rounds instead of truncating, grayscale and RGBA inputs are normalised to RGB, and a batch is split so each frame becomes one reference image. Each PNG goes to POST /v1/uploads, and the returned URLs go into the generate request as image_urls.
The way back applies ImageOps.exif_transpose before converting, so a rotated JPEG from the server does not arrive sideways, then adds the batch dimension:
def bytes_to_tensor(data: bytes):
import torch
return torch.from_numpy(bytes_to_array(data))[None, ...]
torch is imported inside the function so the rest of the module (and its tests) runs without it.
Returning ComfyUI's core VIDEO type
Recent ComfyUI has a first-class VIDEO type that core nodes such as Save Video accept. Its location has moved between versions, so the pack tries both known paths and degrades gracefully:
def video_from_file(path: str):
try:
from comfy_api.latest import InputImpl
return InputImpl.VideoFromFile(path)
except Exception:
pass
try:
from comfy_api.input_impl import VideoFromFile
return VideoFromFile(path)
except Exception:
log.warning("Vellria: this ComfyUI has no VIDEO type; returning only the file path")
return None
The video node always writes the file to ComfyUI/output/vellria/ and returns both VIDEO and a file_path string, so it is useful on older installs too. It is an OUTPUT_NODE and returns a ui payload in the same shape the core preview uses, which gives an inline preview in the node without extra frontend code.
The extension (.webm or .mp4) is chosen from the file's magic bytes rather than trusted from a header.
Keeping the API key out of saved workflows
This is the one I would push every API node author to think about. ComfyUI saves every widget value into the workflow JSON, and that JSON is embedded in the metadata of every PNG saved with Save Image. If your node has an api_key text widget, the key travels with every image your users post online.
The pack resolves the key in this order, first non-empty value wins:
for candidate in (
os.environ.get("VELLRIA_API_KEY"),
_read_config(config_path).get("api_key"),
node_key,
):
key = _clean(candidate)
if key:
return key
The environment variable and a gitignored config.json beat the optional key node on purpose, so a shared workflow never needs to contain a key. The key node exists for convenience, with a tooltip that says plainly that its value is saved into the workflow file.
Two smaller guards in the HTTP client: the Authorization header is only attached when the request URL has the same scheme and host as the configured API (so following an absolute output URL to some other host never leaks it), and the client's __repr__ omits the key so it can't show up in a traceback or log line.
Install and a minimal example
The pack is registered on the Comfy Registry as vellria; the ComfyUI-Manager listing is coming once the first version is approved. Until then, install with git:
cd ComfyUI/custom_nodes
git clone https://github.com/vellria/comfyui-vellria
pip install -r comfyui-vellria/requirements.txt # only "requests"
export VELLRIA_API_KEY=vll_... # Windows: set VELLRIA_API_KEY=vll_...
Restart ComfyUI and the nodes appear under the Vellria category. A minimal text-to-image graph is two nodes: Vellria Image (prompt, model, aspect ratio, resolution, seed) wired into a core Save Image.
The repo's example_workflows/ folder has that graph plus image editing with a Load Image reference, text to video, and image to video; drag a JSON file onto the canvas to load it.
Each generation uses credits from your account balance. One ComfyUI behaviour helps here: a node only re-runs when an input changes, so queueing the same graph twice returns the cached output and costs nothing. Change the prompt or seed to get a new result.
Testing without spending anything
All HTTP calls in the test suite are mocked, so pytest never touches the network. Tensor tests are skipped when torch isn't installed. Keeping request-body building in pure functions (build_image_body, build_video_body) made most of the validation testable as plain dictionaries in, dictionaries out.
If you are building something similar and spot a better way to handle any of this, issues and pull requests are welcome at github.com/vellria/comfyui-vellria.
Comments
No comments yet. Start the discussion.