### Asynchronous Client Quick Start Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Demonstrates how to initialize, connect, set parameters, generate images, and close the asynchronous ComfyUI client. ```APIDOC ## Asynchronous Client Quick Start ```python import asyncio from comfyuiclient import ComfyUIClientAsync async def main(): # Initialize async client client = ComfyUIClientAsync("localhost:8188", "workflow.json") await client.connect() # Set parameters (all async) await client.set_data(key='KSampler', seed=12345) await client.set_data(key='CLIP Text Encode Positive', text="beautiful landscape") # Generate images results = await client.generate(["Result Image"]) for key, image in results.items(): image.save(f"{key}.png") await client.close() asyncio.run(main()) ``` ``` -------------------------------- ### Install ComfyUI API Client Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Install the client library using pip. Ensure you have the required packages installed. ```bash pip install comfyui-workflow-client ``` -------------------------------- ### Run Demo Script Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/TEST_README.md Execute the demo script to see practical usage examples for all client and format combinations. ```bash python demo_usage.py ``` -------------------------------- ### Synchronous Client Quick Start Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Demonstrates how to initialize, connect, set parameters, generate images, and close the synchronous ComfyUI client. ```APIDOC ## Synchronous Client Quick Start ```python from comfyuiclient import ComfyUIClient # Initialize client (supports both workflow.json and workflow_api.json) client = ComfyUIClient("localhost:8188", "workflow.json") client.connect() # Set parameters client.set_data(key='KSampler', seed=12345) client.set_data(key='CLIP Text Encode Positive', text="beautiful landscape") # Generate images results = client.generate(["Result Image"]) for key, image in results.items(): image.save(f"{key}.png") client.close() ``` ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/CONTRIBUTING.md Install pre-commit hooks to automatically format and lint code before commits. ```bash pre-commit install ``` -------------------------------- ### Install Dependencies Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/TEST_README.md Install the required Python packages for the ComfyUI client tests. ```bash pip install -r requirements.txt ``` -------------------------------- ### Asynchronous Client Quick Start Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Initialize and use the asynchronous ComfyUI client. Connect to the server, set node parameters, generate images, and close the connection using async/await. ```python import asyncio from comfyuiclient import ComfyUIClientAsync async def main(): # Initialize async client client = ComfyUIClientAsync("localhost:8188", "workflow.json") await client.connect() # Set parameters (all async) await client.set_data(key='KSampler', seed=12345) await client.set_data(key='CLIP Text Encode Positive', text="beautiful landscape") # Generate images results = await client.generate(["Result Image"]) for key, image in results.items(): image.save(f"{key}.png") await client.close() asyncio.run(main()) ``` -------------------------------- ### Synchronous Client Quick Start Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Initialize and use the synchronous ComfyUI client. Connect to the server, set node parameters, generate images, and close the connection. ```python from comfyuiclient import ComfyUIClient # Initialize client (supports both workflow.json and workflow_api.json) client = ComfyUIClient("localhost:8188", "workflow.json") client.connect() # Set parameters client.set_data(key='KSampler', seed=12345) client.set_data(key='CLIP Text Encode Positive', text="beautiful landscape") # Generate images results = client.generate(["Result Image"]) for key, image in results.items(): image.save(f"{key}.png") client.close() ``` -------------------------------- ### Install development dependencies Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/CONTRIBUTING.md Install the project's development dependencies, including the package itself in editable mode. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Install Missing Dependencies Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/TEST_README.md Install essential Python packages if you encounter missing dependency errors. ```bash pip install requests aiohttp pillow ``` -------------------------------- ### Batch Processing with ComfyUIClient Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Run multiple generations sequentially, updating parameters for each iteration. Ensure the client is connected before starting and closed afterward. Handles potential exceptions during generation. ```python from comfyuiclient import ComfyUIClient import random PROMPTS = [ "sunset over mountains, golden hour, photorealistic", "dense rainforest, morning mist, cinematic", "arctic tundra, northern lights, long exposure", ] client = ComfyUIClient("localhost:8188", "workflow_api.json") client.connect() try: for i, prompt in enumerate(PROMPTS): client.set_data(key="CLIP Text Encode Positive", text=prompt) client.set_data(key="KSampler", seed=random.randint(0, 2**32)) client.set_data(key="KSampler", input_key="steps", input_value=20) results = client.generate(["Result Image"]) output_path = f"batch_{{i:03d}}.png" results["Result Image"].save(output_path) print(f"[{i+1}/{len(PROMPTS)}] Saved {output_path}") # Expected output: # [1/3] Saved batch_000.png # [2/3] Saved batch_001.png # [3/3] Saved batch_002.png except Exception as e: print(f"Batch failed at iteration: {e}") finally: client.close() ``` -------------------------------- ### ComfyUIClientAsync - Asynchronous Client Usage Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Use the asynchronous client for non-blocking operations. This example demonstrates setting parameters and generating an image asynchronously. Requires an event loop to run. ```python import asyncio, random, sys from comfyuiclient import ComfyUIClientAsync async def generate_image(): client = ComfyUIClientAsync("localhost:8188", "workflow.json") await client.connect() try: await client.set_data(key="KSampler", seed=random.randint(0, sys.maxsize)) await client.set_data(key="CLIP Text Encode Positive", text="a neon-lit cyberpunk alley") await client.set_data(key="KSampler", input_key="steps", input_value=30) results = await client.generate(["Result Image"]) for node_name, image in results.items(): image.save(f"{node_name}_async.png") print(f"Saved {node_name}_async.png") # Expected output: # Saved Result Image_async.png except ConnectionError as e: print(f"Server unreachable: {e}") finally: await client.close() asyncio.run(generate_image()) ``` -------------------------------- ### set_data() - Set Workflow Node Parameters Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Explains the `set_data` method for modifying workflow node parameters, including text prompts, seeds, image uploads, and numeric values, with examples for various node types. ```APIDOC ## `set_data()` — Set Workflow Node Parameters `set_data(key, *, text, seed, image, number, value, input_key, input_value)` mutates the in-memory workflow prompt for the node identified by `key` (matched against `_meta.title` first, then `class_type`). Multiple keyword arguments can be passed in a single call; unset arguments are ignored. ```python from comfyuiclient import ComfyUIClient from PIL import Image client = ComfyUIClient("localhost:8188", "workflow_api.json") client.connect() # Text prompt client.set_data(key="CLIP Text Encode Positive", text="golden hour over the ocean") client.set_data(key="CLIP Text Encode Negative", text="blurry, low quality, watermark") # Sampler configuration client.set_data(key="KSampler", seed=42) client.set_data(key="KSampler", input_key="steps", input_value=25) client.set_data(key="KSampler", input_key="cfg", input_value=7.5) client.set_data(key="KSampler", input_key="sampler_name", input_value="euler_ancestral") # Latent image dimensions client.set_data(key="EmptyLatentImage", input_key="width", input_value=768) client.set_data(key="EmptyLatentImage", input_key="height", input_value=512) # Upload a PIL image to a LoadImage node input_img = Image.open("reference.png") client.set_data(key="LoadImage", image=input_img) # Image is uploaded to the server's /upload/image endpoint automatically results = client.generate(["Result Image"]) results["Result Image"].save("output.png") client.close() ``` ``` -------------------------------- ### Initialize and Use ComfyUI Client Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/docs/index.md Demonstrates how to initialize the ComfyUIClient, connect to the API, set parameters for nodes, generate images, and close the connection. Ensure the ComfyUI server is running and accessible at the specified address. ```python from comfyuiclient import ComfyUIClient # Initialize client client = ComfyUIClient("localhost:8188", "workflow.json") client.connect() # Set parameters client.set_data(key='KSampler', seed=12345) client.set_data(key='CLIP Text Encode Positive', text="beautiful landscape") # Generate images results = client.generate(["Result Image"]) for key, image in results.items(): image.save(f"{key}.png") client.close() ``` -------------------------------- ### Create and activate virtual environment Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/CONTRIBUTING.md Set up a Python virtual environment for development. Use 'venv\Scripts\activate' on Windows. ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate ``` -------------------------------- ### Initialize ComfyUI Client Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Instantiate the ComfyUI client with server address and workflow file. Debug mode can be enabled for verbose output. ```python # Basic initialization client = ComfyUIClient(server_address, workflow_file) # With debug mode client = ComfyUIClient(server_address, workflow_file, debug=True) ``` -------------------------------- ### Clone the repository and navigate Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/CONTRIBUTING.md Clone the ComfyUI API Client repository and change the directory to the project root. ```bash git clone https://github.com/sugarkwork/Comfyui_api_client.git cd Comfyui_api_client ``` -------------------------------- ### Connect to ComfyUI Server Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Establish a connection to the ComfyUI server. Use `await` for the asynchronous client. ```python # Sync client.connect() # Async await client.connect() ``` -------------------------------- ### Run Test Suite Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Execute the client's test suite using Python. Different scripts cover basic functionality, error handling, enhanced features, and format conversion. ```bash # Basic functionality tests python test_workflow_loading.py # Error handling tests python test_error_handling.py # Enhanced features tests python test_enhanced_features.py # Format conversion tests python test_conversion.py ``` -------------------------------- ### Run Comprehensive Tests Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/TEST_README.md Execute the main test script to validate all client/format combinations and server connectivity. ```bash python test_comfyui_client.py ``` -------------------------------- ### Client Initialization Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Initializes the ComfyUI client with server address and workflow file, with an option for debug mode. ```APIDOC ## Client Initialization ```python # Basic initialization client = ComfyUIClient(server_address, workflow_file) # With debug mode client = ComfyUIClient(server_address, workflow_file, debug=True) ``` **Parameters:** - `server_address`: ComfyUI server address (e.g., "localhost:8188") - `workflow_file`: Path to workflow.json or workflow_api.json - `debug`: Enable debug output (default: False) ``` -------------------------------- ### connect() Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Establishes a connection to the ComfyUI server. Supports both synchronous and asynchronous calls. ```APIDOC ## connect() Establishes connection to ComfyUI server. ```python # Sync client.connect() # Async await client.connect() ``` ``` -------------------------------- ### Run Inference and Retrieve Outputs with `generate()` Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Queue prompts, wait for completion, and retrieve specified or all output nodes. Ensure the client is connected and data is set before calling. ```python from comfyuiclient import ComfyUIClient client = ComfyUIClient("localhost:8188", "workflow_api.json") client.connect() client.set_data(key="KSampler", seed=99999) client.set_data(key="CLIP Text Encode Positive", text="abstract fractal art") # Retrieve a single named output node results = client.generate(["Result Image"]) print(results.keys()) # dict_keys(['Result Image']) results["Result Image"].save("fractal.png") # Retrieve multiple output nodes results = client.generate(["Preview", "Result Image"]) for name, img in results.items(): img.save(f"{name}.png") # Retrieve all output nodes (pass nothing) all_results = client.generate() print(f"Total outputs: {len(all_results)}") client.close() ``` -------------------------------- ### Instantiate ComfyUIClient with Workflow File Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Instantiate the client with either a standard workflow file or an API-ready JSON format. The client automatically detects and handles both. ```python client1 = ComfyUIClient("localhost:8188", "workflow.json") # Auto-converted client2 = ComfyUIClient("localhost:8188", "workflow_api.json") # Direct use ``` -------------------------------- ### ComfyUIClient - Synchronous Client Usage Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Demonstrates how to instantiate and use the synchronous ComfyUIClient for setting node parameters, generating images, and handling potential connection or timeout errors. ```APIDOC ## ComfyUIClient - Synchronous Client `ComfyUIClient(server, prompt_file, debug=False)` creates a synchronous client backed by a `requests.Session`. It loads and auto-converts the workflow on instantiation. `connect()` opens the session, `close()` releases it. ```python from comfyuiclient import ComfyUIClient import random, sys client = ComfyUIClient("localhost:8188", "workflow.json", debug=True) client.connect() try: client.set_data(key="KSampler", seed=random.randint(0, sys.maxsize)) client.set_data(key="CLIP Text Encode Positive", text="a misty mountain at dawn") client.set_data(key="EmptyLatentImage", input_key="width", input_value=768) results = client.generate(["Result Image"]) for node_name, image in results.items(): image.save(f"{node_name}.png") print(f"Saved {node_name}.png ({image.size})") # Expected output: # Set data for KSampler ... # Saved Result Image.png (512, 512) except ConnectionError as e: print(f"Connection failed: {e}") except TimeoutError as e: print(f"Timed out (>5 min): {e}") finally: client.close() ``` ``` -------------------------------- ### Debug Tip: Use Format Conversion Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Convert your workflow to the API format to better understand its structure and identify potential issues before programmatic use. ```python api_format = convert_workflow_to_api("workflow.json") print(json.dumps(api_format, indent=2)) ``` -------------------------------- ### Format and sort code Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/CONTRIBUTING.md Apply code formatting with Black and import sorting with isort to maintain code style consistency. ```bash black comfyuiclient tests isort comfyuiclient tests ``` -------------------------------- ### Debug Tip: Test Workflow in ComfyUI Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Before using the client, ensure your workflow functions correctly within the ComfyUI graphical interface. ```text Test workflow in ComfyUI first ``` -------------------------------- ### Run the test suite Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/CONTRIBUTING.md Execute the project's tests using pytest. Ensure all tests pass before submitting a pull request. ```bash pytest tests/ ``` -------------------------------- ### set_data() - Configure Workflow Nodes Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Demonstrates setting various parameters for workflow nodes using the `set_data` method. Supports text prompts, seeds, sampler settings, image dimensions, and image uploads. ```python from comfyuiclient import ComfyUIClient from PIL import Image client = ComfyUIClient("localhost:8188", "workflow_api.json") client.connect() # Text prompt client.set_data(key="CLIP Text Encode Positive", text="golden hour over the ocean") client.set_data(key="CLIP Text Encode Negative", text="blurry, low quality, watermark") # Sampler configuration client.set_data(key="KSampler", seed=42) client.set_data(key="KSampler", input_key="steps", input_value=25) client.set_data(key="KSampler", input_key="cfg", input_value=7.5) client.set_data(key="KSampler", input_key="sampler_name", input_value="euler_ancestral") # Latent image dimensions client.set_data(key="EmptyLatentImage", input_key="width", input_value=768) client.set_data(key="EmptyLatentImage", input_key="height", input_value=512) # Upload a PIL image to a LoadImage node input_img = Image.open("reference.png") client.set_data(key="LoadImage", image=input_img) # Image is uploaded to the server's /upload/image endpoint automatically results = client.generate(["Result Image"]) results["Result Image"].save("output.png") client.close() ``` -------------------------------- ### generate() — Run Inference and Retrieve Outputs Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Queues the current prompt, waits for completion, and returns a dictionary of output nodes keyed by node name. Can retrieve all outputs or specific ones. ```APIDOC ## `generate()` — Run Inference and Retrieve Outputs `generate(node_names=None)` queues the current prompt, waits for completion, and returns a `dict[str, PIL.Image.Image | str]` keyed by node name. If `node_names` is `None` it returns all output nodes; otherwise only the specified nodes are returned. ```python from comfyuiclient import ComfyUIClient client = ComfyUIClient("localhost:8188", "workflow_api.json") client.connect() client.set_data(key="KSampler", seed=99999) client.set_data(key="CLIP Text Encode Positive", text="abstract fractal art") # Retrieve a single named output node results = client.generate(["Result Image"]) print(results.keys()) # dict_keys(['Result Image']) results["Result Image"].save("fractal.png") # Retrieve multiple output nodes results = client.generate(["Preview", "Result Image"]) for name, img in results.items(): img.save(f"{name}.png") # Retrieve all output nodes (pass nothing) all_results = client.generate() print(f"Total outputs: {len(all_results)}") client.close() ``` ``` -------------------------------- ### ComfyUIClient - Synchronous Client Usage Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Instantiate and use the synchronous client for basic image generation. Ensure the server is running and the workflow file exists. Handles connection, parameter setting, generation, and cleanup. ```python from comfyuiclient import ComfyUIClient import random, sys client = ComfyUIClient("localhost:8188", "workflow.json", debug=True) client.connect() try: client.set_data(key="KSampler", seed=random.randint(0, sys.maxsize)) client.set_data(key="CLIP Text Encode Positive", text="a misty mountain at dawn") client.set_data(key="EmptyLatentImage", input_key="width", input_value=768) results = client.generate(["Result Image"]) for node_name, image in results.items(): image.save(f"{node_name}.png") print(f"Saved {node_name}.png ({image.size})") # Expected output: # Set data for KSampler ... # Saved Result Image.png (512, 512) except ConnectionError as e: print(f"Connection failed: {e}") except TimeoutError as e: print(f"Timed out (>5 min): {e}") finally: client.close() ``` -------------------------------- ### ComfyUIClient Context Manager Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Utilize the context manager pattern for automatic connection and cleanup of the ComfyUI client. Ensures `connect()` and `close()` are called reliably. ```python class ComfyUIContextManager: def __init__(self, *args, **kwargs): self.client = ComfyUIClient(*args, **kwargs) def __enter__(self): self.client.connect() return self.client def __exit__(self, exc_type, exc_val, exc_tb): self.client.close() # Usage with ComfyUIContextManager("localhost:8188", "workflow.json") as client: client.set_data(key='KSampler', seed=12345) results = client.generate(["Result Image"]) ``` -------------------------------- ### ComfyUIClientAsync - Asynchronous Client Usage Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Illustrates the usage of the asynchronous ComfyUIClientAsync, highlighting its coroutine-based methods for connecting, setting parameters, generating images, and handling errors. ```APIDOC ## ComfyUIClientAsync — Asynchronous Client `ComfyUIClientAsync(server, prompt_file, debug=False)` provides the same interface as the synchronous client, but every I/O method is a coroutine. It uses `aiohttp` internally and communicates with the server over a WebSocket connection for real-time execution updates. ```python import asyncio, random, sys from comfyuiclient import ComfyUIClientAsync async def generate_image(): client = ComfyUIClientAsync("localhost:8188", "workflow.json") await client.connect() try: await client.set_data(key="KSampler", seed=random.randint(0, sys.maxsize)) await client.set_data(key="CLIP Text Encode Positive", text="a neon-lit cyberpunk alley") await client.set_data(key="KSampler", input_key="steps", input_value=30) results = await client.generate(["Result Image"]) for node_name, image in results.items(): image.save(f"{node_name}_async.png") print(f"Saved {node_name}_async.png") # Expected output: # Saved Result Image_async.png except ConnectionError as e: print(f"Server unreachable: {e}") finally: await client.close() asyncio.run(generate_image()) ``` ``` -------------------------------- ### Standalone Workflow Format Conversion with `convert_workflow_to_api()` Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Converts a ComfyUI UI-format workflow to the API format required by the `/prompt` endpoint. Accepts either a file path or a pre-loaded dictionary. The converted output can be inspected or saved for reuse. ```python from comfyuiclient import convert_workflow_to_api import json # Convert from file path api_format = convert_workflow_to_api("workflow.json") print(json.dumps(api_format, indent=2)) # Output: {"3": {"class_type": "KSampler", "inputs": {"seed": 42, ...}, "_meta": {...}}, ...} # Convert from dict with open("workflow.json") as f: workflow_dict = json.load(f) api_format = convert_workflow_to_api(workflow_dict) # Inspect converted node for node_id, node_data in api_format.items(): print(f"[{node_id}] {node_data['class_type']} -> inputs: {list(node_data['inputs'].keys())}") # Save converted result for reuse with open("workflow_converted.json", "w") as f: json.dump(api_format, f, indent=2) ``` -------------------------------- ### Batch Processing with ComfyUIClient Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Iterate through multiple prompts and seeds to generate images in batches. Saves each generated image with a unique filename. ```python import random prompts = ["sunset over mountains", "city at night", "forest lake"] seeds = [random.randint(0, 2**32) for _ in range(3)] client = ComfyUIClient("localhost:8188", "workflow.json") client.connect() for i, (prompt, seed) in enumerate(zip(prompts, seeds)): client.set_data(key='CLIP Text Encode Positive', text=prompt) client.set_data(key='KSampler', seed=seed) results = client.generate(["Result Image"]) for key, image in results.items(): image.save(f"output_{i}_{key}.png") client.close() ``` -------------------------------- ### Run linting checks Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/CONTRIBUTING.md Perform linting using flake8 and type checking with mypy to ensure code quality. ```bash flake8 comfyuiclient tests mypy comfyuiclient ``` -------------------------------- ### Async Concurrent Generation with ComfyUIClientAsync Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Run multiple independent generation tasks concurrently using `asyncio.gather`. Each task uses its own `ComfyUIClientAsync` instance. Ensure clients are connected and closed within each async task. ```python import asyncio, random from comfyuiclient import ComfyUIClientAsync async def run_generation(prompt: str, seed: int, out_file: str): client = ComfyUIClientAsync("localhost:8188", "workflow_api.json") await client.connect() try: await client.set_data(key="CLIP Text Encode Positive", text=prompt) await client.set_data(key="KSampler", seed=seed) results = await client.generate(["Result Image"]) results["Result Image"].save(out_file) print(f"Saved {out_file}") finally: await client.close() async def main(): tasks = [ run_generation("cyberpunk street at night", 1001, "cyber.png"), run_generation("impressionist garden in spring", 2002, "garden.png"), run_generation("deep space nebula, 8k", 3003, "nebula.png"), ] await asyncio.gather(*tasks) # All three images generated concurrently # Expected output (order may vary): # Saved cyber.png # Saved garden.png # Saved nebula.png asyncio.run(main()) ``` -------------------------------- ### Troubleshooting Connection Refused Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md A `ConnectionError` indicates the client could not reach the ComfyUI server. Verify the server is running, check firewall rules, and confirm the port number. ```text ConnectionError: Failed to connect to ComfyUI server ``` -------------------------------- ### reload() — Reload Workflow File at Runtime Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Re-reads the workflow file from disk and re-runs format conversion if the file has changed. This is useful for hot-swapping workflow configurations without needing to recreate the client instance. ```APIDOC ## `reload()` — Reload Workflow File at Runtime `reload()` re-reads `prompt_file` from disk and re-runs format conversion if the file has changed. Useful for hot-swapping workflow configurations without recreating the client instance. ```python from comfyuiclient import ComfyUIClient import json client = ComfyUIClient("localhost:8188", "workflow.json") client.connect() # First generation with initial workflow client.set_data(key="KSampler", seed=1) client.generate(["Result Image"])["Result Image"].save("gen1.png") # Modify workflow file externally (e.g., change checkpoint) workflow = json.load(open("workflow.json")) # ... modify workflow dict ... json.dump(workflow, open("workflow.json", "w")) # Reload without restarting client.reload() # Second generation with updated workflow client.set_data(key="KSampler", seed=2) client.generate(["Result Image"])["Result Image"].save("gen2.png") client.close() ``` ``` -------------------------------- ### Reload Workflow File at Runtime with `reload()` Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Re-reads the workflow file and re-runs format conversion without restarting the client. Useful for hot-swapping configurations. Ensure the workflow file is modified externally before calling `reload()`. ```python from comfyuiclient import ComfyUIClient import json client = ComfyUIClient("localhost:8188", "workflow.json") client.connect() # First generation with initial workflow client.set_data(key="KSampler", seed=1) client.generate(["Result Image"])["Result Image"].save("gen1.png") # Modify workflow file externally (e.g., change checkpoint) workflow = json.load(open("workflow.json")) # ... modify workflow dict ... json.dump(workflow, open("workflow.json", "w")) # Reload without restarting client.reload() # Second generation with updated workflow client.set_data(key="KSampler", seed=2) client.generate(["Result Image"])["Result Image"].save("gen2.png") client.close() ``` -------------------------------- ### convert_workflow_to_api() — Standalone Format Conversion Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Converts a ComfyUI UI-format workflow (exported via "Save" in the web interface) to the API format required by the `/prompt` endpoint. This function can accept either a file path string or a pre-loaded dictionary. ```APIDOC ## `convert_workflow_to_api()` — Standalone Format Conversion `convert_workflow_to_api(workflow_json)` converts a ComfyUI UI-format workflow (exported via "Save" in the web interface, containing `nodes` and `links` keys) to the API format required by the `/prompt` endpoint. Accepts either a file path string or a pre-loaded dict. ```python from comfyuiclient import convert_workflow_to_api import json # Convert from file path api_format = convert_workflow_to_api("workflow.json") print(json.dumps(api_format, indent=2)) # Output: {"3": {"class_type": "KSampler", "inputs": {"seed": 42, ...}, "_meta": {...}}, ...} # Convert from dict with open("workflow.json") as f: workflow_dict = json.load(f) api_format = convert_workflow_to_api(workflow_dict) # Inspect converted node for node_id, node_data in api_format.items(): print(f"[{node_id}] {node_data['class_type']} -> inputs: {list(node_data['inputs'].keys())}") # Save converted result for reuse with open("workflow_converted.json", "w") as f: json.dump(api_format, f, indent=2) ``` ``` -------------------------------- ### Create a new Git branch Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/CONTRIBUTING.md Use this command to create a new branch for your feature or fix. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Debug Tip: Check Node Names Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Use debug mode to inspect node IDs and titles within your workflow. This helps in correctly identifying nodes for parameter setting. ```python client = ComfyUIClient("localhost:8188", "workflow.json", debug=True) # Debug output will show available node IDs and titles ``` -------------------------------- ### Generate Images from Nodes Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Trigger image generation for specified nodes or all output nodes. Results are returned as a dictionary mapping node names to PIL Image objects. ```python # Generate from specific nodes results = client.generate(["Result Image", "Preview"]) # Generate from all output nodes results = client.generate() # Results are returned as {node_name: PIL.Image} dictionary for node_name, image in results.items(): image.save(f"{node_name}.png") ``` -------------------------------- ### Enable Debug Mode in ComfyUIClient Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Enable debug mode during client instantiation to receive detailed logging for workflow loading, parameter setting, node lookup, and error details. ```python client = ComfyUIClient("localhost:8188", "workflow.json", debug=True) ``` -------------------------------- ### generate(node_names=None) Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Generates outputs from specified nodes in the workflow. Can generate from all output nodes if `node_names` is not provided. Results are returned as a dictionary of PIL Images. ```APIDOC ## generate(node_names=None) Generates outputs from specified nodes. ```python # Generate from specific nodes results = client.generate(["Result Image", "Preview"]) # Generate from all output nodes results = client.generate() # Results are returned as {node_name: PIL.Image} dictionary for node_name, image in results.items(): image.save(f"{node_name}.png") ``` ``` -------------------------------- ### convert_workflow_to_api(workflow_json) Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Converts a ComfyUI workflow JSON file or dictionary into the format required by the API. ```APIDOC ## convert_workflow_to_api(workflow_json) Converts ComfyUI workflow format to API format. ```python from comfyuiclient import convert_workflow_to_api # Convert file api_format = convert_workflow_to_api("workflow.json") # Convert dict with open("workflow.json") as f: workflow_data = json.load(f) api_format = convert_workflow_to_api(workflow_data) ``` ``` -------------------------------- ### set_data(key, **kwargs) Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Sets parameters for specific nodes in the workflow. Supports various parameter types including text, seeds, images, and arbitrary key-value pairs. ```APIDOC ## set_data(key, **kwargs) Sets parameters for workflow nodes. ```python # Basic parameters client.set_data(key='KSampler', seed=12345) client.set_data(key='CLIP Text Encode Positive', text="prompt text") # Advanced parameters client.set_data(key='KSampler', input_key='steps', input_value=25) client.set_data(key='EmptyLatentImage', number=512.0) client.set_data(key='SomeNode', value=1.5) # Image upload from PIL import Image image = Image.open("input.png") client.set_data(key='LoadImage', image=image) ``` **Parameters:** - `key`: Node title or class_type - `text`: Text input for text nodes - `seed`: Seed value for generation nodes - `image`: PIL Image object for image inputs - `number`: Numeric parameter (mapped to 'Number' input) - `value`: Numeric parameter (mapped to 'value' input) - `input_key`/`input_value`: Arbitrary key-value pairs ``` -------------------------------- ### Troubleshooting Key Not Found Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md A `Key not found` error means a specified node name is incorrect. Check the node title in the ComfyUI interface, consider using `class_type`, or enable debug mode. ```text Key not found: NodeName ``` -------------------------------- ### Close Client Connection Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Close the connection to the ComfyUI server and release resources. Use `await` for the asynchronous client. ```python # Sync client.close() # Async await client.close() ``` -------------------------------- ### Dynamic Workflow Updates with ComfyUIClient Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Modify workflow parameters and dynamically reload the workflow if it has been changed externally. This allows for updates without restarting the client. ```python client = ComfyUIClient("localhost:8188", "workflow.json") client.connect() # Initial generation client.set_data(key='KSampler', seed=12345) results = client.generate(["Result Image"]) # Modify workflow file externally, then reload client.reload() # Use updated workflow client.set_data(key='KSampler', seed=67890) results = client.generate(["Result Image"]) client.close() ``` -------------------------------- ### reload() Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Reloads the workflow file, which is useful for dynamic workflows where the file might be updated externally. ```APIDOC ## reload() Reloads the workflow file (useful for dynamic workflows). ```python client.reload() ``` ``` -------------------------------- ### Resolve Node ID from Name with `find_key_by_title()` Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Searches the loaded prompt for a node by its title or class type. Returns the node's string ID key or None if not found. Useful for inspecting loaded workflows. Debug mode provides additional output for missing nodes. ```python from comfyuiclient import ComfyUIClient client = ComfyUIClient("localhost:8188", "workflow_api.json", debug=True) # Look up by title (as set in the ComfyUI editor) node_id = client.find_key_by_title("Result Image") print(f"Node ID for 'Result Image': {node_id}") # e.g. "9" # Look up by class_type node_id = client.find_key_by_title("KSampler") print(f"Node ID for 'KSampler': {node_id}") # e.g. "3" # Returns None for unknown nodes (debug=True also prints a message) missing = client.find_key_by_title("NonExistentNode") print(f"Missing node: {missing}") # None # Debug output: Key not found: NonExistentNode ``` -------------------------------- ### close() Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Closes the connection to the ComfyUI server and cleans up any associated resources. Supports both synchronous and asynchronous calls. ```APIDOC ## close() Closes the connection and cleans up resources. ```python # Sync client.close() # Async await client.close() ``` ``` -------------------------------- ### Set Node Parameters Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Update parameters for specific nodes in the workflow. Supports basic, advanced, and image input types. ```python # Basic parameters client.set_data(key='KSampler', seed=12345) client.set_data(key='CLIP Text Encode Positive', text="prompt text") # Advanced parameters client.set_data(key='KSampler', input_key='steps', input_value=25) client.set_data(key='EmptyLatentImage', number=512.0) client.set_data(key='SomeNode', value=1.5) # Image upload from PIL import Image image = Image.open("input.png") client.set_data(key='LoadImage', image=image) ``` -------------------------------- ### ComfyUIClient Error Handling Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Implement robust error handling for connection, data validation, and timeout issues. Ensure resources are cleaned up in the finally block. ```python try: client = ComfyUIClient("localhost:8188", "workflow.json") client.connect() results = client.generate(["Result Image"]) except ConnectionError as e: print(f"Connection failed: {e}") except ValueError as e: print(f"Invalid data: {e}") except TimeoutError as e: print(f"Operation timed out: {e}") except Exception as e: print(f"Unexpected error: {e}") finally: client.close() ``` -------------------------------- ### Reload Workflow File Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Reload the workflow file without restarting the client. Useful for dynamic workflow updates. ```python client.reload() ``` -------------------------------- ### Convert Workflow to API Format Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md Utility function to convert ComfyUI workflow JSON to the API format. Can process file paths or dictionary objects. ```python from comfyuiclient import convert_workflow_to_api # Convert file api_format = convert_workflow_to_api("workflow.json") # Convert dict with open("workflow.json") as f: workflow_data = json.load(f) api_format = convert_workflow_to_api(workflow_data) ``` -------------------------------- ### find_key_by_title() — Resolve Node ID from Name Source: https://context7.com/sugarkwork/comfyui_api_client/llms.txt Searches the loaded prompt for a node whose `class_type` or `_meta.title` matches the provided `target_title`. Returns the node's string ID key or `None` if not found. This method is used internally but can also be called directly for inspection. ```APIDOC ## `find_key_by_title()` — Resolve Node ID from Name `find_key_by_title(target_title)` searches the loaded prompt for a node whose `class_type` or `_meta.title` matches `target_title` (case-sensitive, whitespace-stripped). Returns the node's string ID key or `None` if not found. Used internally by `set_data()` and `generate()`, but also callable directly for inspection. ```python from comfyuiclient import ComfyUIClient client = ComfyUIClient("localhost:8188", "workflow_api.json", debug=True) # Look up by title (as set in the ComfyUI editor) node_id = client.find_key_by_title("Result Image") print(f"Node ID for 'Result Image': {node_id}") # e.g. "9" # Look up by class_type node_id = client.find_key_by_title("KSampler") print(f"Node ID for 'KSampler': {node_id}") # e.g. "3" # Returns None for unknown nodes (debug=True also prints a message) missing = client.find_key_by_title("NonExistentNode") print(f"Missing node: {missing}") # None # Debug output: Key not found: NonExistentNode ``` ``` -------------------------------- ### Troubleshooting Timeout Errors Source: https://github.com/sugarkwork/comfyui_api_client/blob/main/README.md A `TimeoutError` occurs when a prompt takes too long to complete. This can happen with complex workflows. Check server performance and workflow validity. ```text TimeoutError: Timeout waiting for prompt to complete ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.