# ImageLab External API Documentation **Version:** 2.0 **Base URL:** `http://127.0.0.1:8188` REST API endpoints for executing ComfyScript workflows with real-time progress monitoring. --- ## Table of Contents 1. [Architecture Overview](#architecture-overview) 2. [Directory Structure](#directory-structure) 3. [Quick Start](#quick-start) 4. [API Endpoints](#api-endpoints) 5. [WebSocket Events](#websocket-events) 6. [Workflow System](#workflow-system) 7. [YAML Schema System](#yaml-schema-system) 8. [Resource System](#resource-system) 9. [CLI Commands](#cli-commands) 10. [JavaScript Examples](#javascript-examples) --- ## Architecture Overview The ImageLab External API extends ComfyUI with: - **Workflow Execution**: Execute ComfyScript-based workflows via REST API - **YAML Schema System**: Auto-generated UI schemas from Pydantic models - **Resource Discovery**: List and index models with CivitAI metadata - **Progress Broadcasting**: Real-time updates via WebSocket binary events - **Hot Reloading**: Workflows reload from disk on each execution ### Technology Stack | Component | Technology | | ------------- | ---------------------- | | Server | ComfyUI (aiohttp) | | Workflows | ComfyScript + Pydantic | | Schema | YAML (auto-generated) | | Validation | Pydantic models | | Communication | REST + WebSocket | --- ## Directory Structure ``` external-api/ ├── __init__.py # Entry point, registers routes ├── __main__.py # CLI entry point (python -m external-api) ├── cli.py # CLI commands (generate, validate, list, watch) ├── schema_generator.py # YAML schema generation from Pydantic ├── workflows.py # Workflow registry and discovery ├── routes.py # API endpoint definitions ├── resources.py # Model discovery and indexing ├── progress.py # WebSocket progress broadcasting ├── parameters.py # Shared Annotated type definitions ├── base.py # BaseWorkflow class ├── resources/ # Model index files (.index) └── workflows/ # Individual workflow scripts ├── basic_sdxl.py # Workflow code + WorkflowParams ├── basic_sdxl.yaml # Auto-generated UI schema └── ... ``` --- ## Quick Start ### Execute a Workflow ```bash curl -X POST http://localhost:8188/imagelab/workflow/basic_sdxl \ -H "Content-Type: application/json" \ -d '{ "prompt": "a beautiful sunset over mountains", "negativePrompt": "blurry, low quality", "checkpoints": ["model.safetensors"], "seed": 42, "steps": 20, "width": 1024, "height": 1024, "cfg": 8.0 }' ``` ### List Available Workflows ```bash curl http://localhost:8188/imagelab/workflows ``` ### Get Workflow Parameters ```bash curl http://localhost:8188/imagelab/workflow/basic_sdxl/parameters ``` --- ## API Endpoints ### Workflow Endpoints #### `GET /imagelab/workflows` List all available workflows with metadata. **Response:** ```json { "workflows": [ { "id": "basic_sdxl", "name": "Basic SDXL Text to Image", "description": "Workflow with SDXL presets for quick iteration.", "model_types": ["SDXL"], "category": "Image Generation", "has_parameters": true } ] } ``` --- #### `GET /imagelab/workflow/{workflow_name}/metadata` Get metadata for a specific workflow. **Response:** ```json { "success": true, "workflow": "basic_sdxl", "metadata": { "name": "Basic SDXL Text to Image", "description": "Workflow with SDXL presets for quick iteration.", "model_types": ["SDXL"], "category": "Image Generation", "has_parameters": true } } ``` --- #### `GET /imagelab/workflow/{workflow_name}/parameters` Get the UI parameter schema for a workflow. Returns resolved options from `options_source`. **Response:** ```json { "success": true, "workflow": "basic_sdxl", "parameters": [ { "name": "prompt", "type": "text", "category": "prompts", "multiline": true, "required": true, "label": "Your Creative Prompt", "rows": 4, "placeholder": "Describe your image...", "description": "Enter a detailed description of the image" }, { "name": "sampler", "type": "enum", "options_source": "samplers", "category": "parameters", "default": "euler", "label": "Sampler", "searchable": true, "options": [ { "label": "euler", "apiName": "euler", "metadata": null }, { "label": "euler_ancestral", "apiName": "euler_ancestral", "metadata": null } ] } ] } ``` --- #### `POST /imagelab/workflow/{workflow_name}` Execute a workflow with parameters. **Request:** ```json { "prompt": "a beautiful sunset", "negativePrompt": "blurry", "checkpoints": ["model.safetensors"], "seed": 42, "steps": 20, "width": 1024, "height": 1024, "cfg": 8.0 } ``` **Response:** ```json { "success": true, "workflow": "basic_sdxl", "result": { "prompt_id": "abc123-def456-...", "status": "queued", "parameters": { ... } } } ``` **Error Response:** ```json { "success": false, "type": "ValueError", "error": "Missing required fields: prompt, seed" } ``` --- ### Resource Endpoints #### `GET /imagelab/resources` Get all available resources (models, samplers, schedulers). **Response:** ```json { "success": true, "resources": { "checkpoints": [ { "label": "dreamshaper_8", "apiName": "dreamshaper_8.safetensors", "indexed": true } ], "loras": [...], "vae": [...], "samplers": [ { "label": "euler", "apiName": "euler", "metadata": null } ], "schedulers": [...], "upscale_methods": [...] } } ``` --- #### `GET /imagelab/resources/{resource_type}` Get resources of a specific type. **Types:** `checkpoints`, `loras`, `vae`, `embeddings`, `controlnet`, `samplers`, `schedulers`, `upscale_methods` **Response:** ```json { "success": true, "resource_type": "loras", "items": [ { "label": "my_lora", "apiName": "my_lora.safetensors", "indexed": false } ] } ``` --- #### `POST /imagelab/resources/{resource_type}/index/{filename}` Index a model file (calculate SHA256 hash and fetch CivitAI metadata). **Response:** ```json { "success": true, "resource_type": "checkpoints", "filename": "dreamshaper_8.safetensors", "metadata": { "filename": "dreamshaper_8.safetensors", "hash": "abc123...", "civitai": { "modelId": 4384, "name": "DreamShaper", "baseModel": "SD 1.5" }, "imagelab": {} } } ``` --- #### `POST /imagelab/resources/index-all` Index all unindexed models (background operation at startup by default). **Response:** ```json { "success": true, "message": "Indexing complete", "indexed": { "checkpoints": 3, "loras": 12 } } ``` --- ## WebSocket Events ### Connection ```javascript const ws = new WebSocket("ws://127.0.0.1:8188/ws?clientId=my-app"); ``` ### Binary Event Types | Event Code | Name | Description | | ---------- | ------------------------- | ---------------------------- | | 100 | `IMAGELAB_PROGRESS_EVENT` | Sampler step progress (JSON) | | 101 | `IMAGELAB_PREVIEW_EVENT` | Preview image with metadata | | 102 | `IMAGELAB_WORKFLOW_EVENT` | Workflow lifecycle events | ### Event 100: Progress **Format:** `[4 bytes: event type][JSON payload]` ```json { "event": "sampler_progress", "node_id": "3", "prompt_id": "abc123", "value": 5, "max": 20, "progress_percent": 25.0 } ``` ### Event 101: Preview Image **Format:** `[4 bytes: event type][4 bytes: metadata length][JSON metadata][image bytes]` ```json { "node_id": "3", "prompt_id": "abc123" } ``` ### Event 102: Workflow Event **Format:** `[4 bytes: event type][JSON payload]` ```json { "event": "executing", "data": { "node": "3", "prompt_id": "abc123" } } ``` **Event types:** `executing`, `execution_start`, `executed`, `execution_error`, `execution_cached` ### JavaScript WebSocket Client ```javascript class ImageLabClient { constructor(url = "ws://127.0.0.1:8188/ws") { this.ws = new WebSocket(url); this.handlers = {}; this.ws.onmessage = (event) => { if (event.data instanceof Blob) { this.handleBinary(event.data); } else { this.handleJSON(JSON.parse(event.data)); } }; } async handleBinary(blob) { const buffer = await blob.arrayBuffer(); const view = new DataView(buffer); const eventType = view.getUint32(0, false); // big-endian if (eventType === 100) { // Progress event const json = new TextDecoder().decode(buffer.slice(4)); this.emit("progress", JSON.parse(json)); } else if (eventType === 101) { // Preview image with metadata const metadataLen = view.getUint32(4, false); const metadataJson = new TextDecoder().decode( buffer.slice(8, 8 + metadataLen) ); const metadata = JSON.parse(metadataJson); const imageData = buffer.slice(8 + metadataLen); const imageUrl = URL.createObjectURL(new Blob([imageData])); this.emit("preview", { url: imageUrl, metadata }); } else if (eventType === 102) { // Workflow event const json = new TextDecoder().decode(buffer.slice(4)); this.emit("workflow", JSON.parse(json)); } } handleJSON(data) { this.emit(data.type, data.data); } on(event, handler) { this.handlers[event] = this.handlers[event] || []; this.handlers[event].push(handler); } emit(event, data) { (this.handlers[event] || []).forEach((h) => h(data)); } } // Usage const client = new ImageLabClient(); client.on("progress", (data) => { console.log(`Progress: ${data.progress_percent}%`); }); client.on("preview", ({ url, metadata }) => { document.getElementById("preview").src = url; }); ``` --- ## Workflow System ### Creating a New Workflow 1. Create `workflows/my_workflow.py`: ```python from pydantic import BaseModel, Field from typing import List from comfy_script.runtime import * load('http://127.0.0.1:8188/') from comfy_script.runtime.nodes import * import sys, os sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) from base import BaseWorkflow from parameters import Prompt, NegativePrompt, Checkpoint, Seed, Width, Height WORKFLOW_METADATA = { "name": "My Custom Workflow", "description": "Description of what this workflow does.", "model_types": ["SD1.5", "SDXL"], "category": "Image Generation", } class WorkflowParams(BaseModel): prompt: Prompt negativePrompt: NegativePrompt = "blurry, low quality" checkpoints: Checkpoint seed: Seed width: Width = 512 height: Height = 512 steps: int = Field(default=20, ge=1, le=150) class MyWorkflow(BaseWorkflow): def run(self): params: WorkflowParams = self.params with Workflow(wait=False): model, clip, vae = self.load_checkpoints() # ... your workflow logic preview = PreviewImage(image) return { 'prompt_id': preview.task.prompt_id, 'status': 'queued', 'parameters': self.params.model_dump() } def run_workflow(**kwargs): params = WorkflowParams(**kwargs) workflow = MyWorkflow(params) return workflow.run() ``` 2. Generate the YAML schema: ```bash python -m external-api generate my_workflow ``` 3. Customize the generated `workflows/my_workflow.yaml` as needed. ### Workflow Components | Component | Description | | ------------------- | ---------------------------------------- | | `WORKFLOW_METADATA` | Name, description, model_types, category | | `WorkflowParams` | Pydantic model defining parameters | | `run_workflow()` | Module entry point | | `*.yaml` | Auto-generated UI schema | --- ## YAML Schema System ### Overview UI parameter schemas are auto-generated from Pydantic `WorkflowParams` models using `Annotated` types. The YAML files can be customized and changes are preserved on regeneration. ### Annotated Types (parameters.py) ```python from typing import Annotated, List from pydantic import Field # Text fields Prompt = Annotated[str, Field( json_schema_extra={"ui_type": "text", "category": "prompts", "multiline": True, "rows": 4} )] # Special types Seed = Annotated[int, Field( json_schema_extra={"ui_type": "seed", "category": "parameters"} )] # Enum types (options resolved from resources) Sampler = Annotated[str, Field( json_schema_extra={"ui_type": "enum", "options_source": "samplers", "category": "parameters"} )] # Model selectors Checkpoint = Annotated[List[str], Field( json_schema_extra={"ui_type": "model", "options_source": "checkpoints", "category": "models"} )] # Dimension fields Width = Annotated[int, Field( ge=64, le=2048, multiple_of=8, json_schema_extra={"category": "composition"} )] ``` ### YAML Format ```yaml name: Basic SDXL Text to Image description: Workflow with SDXL presets for quick iteration. category: Image Generation model_types: - SDXL parameters: - name: prompt type: text category: prompts multiline: true required: true label: Your Creative Prompt rows: 4 placeholder: Describe your image... description: Enter a detailed description - name: sampler type: enum options_source: samplers category: parameters default: euler label: Sampler searchable: true - name: width type: int category: composition min: 64 max: 2048 step: 8 default: 1024 label: Width ``` ### Merge Strategy When regenerating YAML schemas: **Preserved** (user customizations): - `label`, `description`, `placeholder` - `rows`, `searchable`, `depends_on` - `options`, `max_selections` **Updated** (from code): - `type`, `default`, `required` - `min`, `max`, `step` - `category`, `options_source` - `multiple`, `params`, `multiline` ### Parameter Types | Type | Description | Properties | | ------------------- | ------------------- | ---------------------------------- | | `text` | Text input | `multiline`, `rows`, `placeholder` | | `int` | Integer | `min`, `max`, `step` | | `float` | Decimal | `min`, `max`, `step` | | `bool` | Boolean toggle | - | | `enum` | Dropdown | `options_source`, `searchable` | | `seed` | Random seed | - | | `model` | Model selector | `options_source`, `multiple` | | `model_with_params` | Model with settings | `options_source`, `params` | ### options_source Values | Source | Description | | ----------------- | ---------------------- | | `samplers` | KSampler samplers | | `schedulers` | KSampler schedulers | | `upscale_methods` | Latent upscale methods | | `checkpoints` | Checkpoint models | | `loras` | LoRA models | | `vae` | VAE models | | `embeddings` | Text embeddings | | `controlnet` | ControlNet models | --- ## Resource System ### Model Discovery Resources are discovered from ComfyUI's configured model folders: ```python # resources.py def get_models_by_type(model_type: str) -> List[Dict]: """Returns list of {label, apiName, indexed}""" ``` ### Model Indexing Models can be indexed to calculate SHA256 hash and fetch CivitAI metadata: ```python # Index file format (.index) { "filename": "model.safetensors", "hash": "sha256...", "civitai": { "modelId": 1234, "name": "Model Name", "baseModel": "SDXL" }, "imagelab": {} } ``` ### Auto-Indexing By default, new models are indexed in a background thread at startup: ```python # __init__.py AUTO_INDEX_ON_STARTUP = True ``` --- ## CLI Commands The CLI is used for managing YAML workflow schemas. ```bash # Generate schema for a workflow python -m external-api generate basic_sdxl # Generate for all workflows python -m external-api generate --all # Preview without writing (dry-run) python -m external-api generate basic_sdxl --dry-run # Validate schema matches code python -m external-api validate basic_sdxl python -m external-api validate --all # List all workflows python -m external-api list # Watch mode (auto-regenerate on file changes) pip install watchdog # required for watch python -m external-api watch ``` ### Watch Mode Monitors the `workflows/` folder and auto-regenerates YAML when `.py` files change: ```bash $ python -m external-api watch Watching for changes in: .../workflows Press Ctrl+C to stop. ✓ basic_sdxl ✓ basic_test1 ✓ test [12:34:56] Regenerating: basic_sdxl ✓ basic_sdxl.yaml updated ``` --- ## JavaScript Examples ### Complete Workflow Execution ```javascript class ImageLabAPI { constructor(baseUrl = "http://127.0.0.1:8188") { this.baseUrl = baseUrl; this.ws = null; this.handlers = {}; } // Connect WebSocket for progress updates connect() { return new Promise((resolve, reject) => { const clientId = `client-${Date.now()}`; this.ws = new WebSocket( `${this.baseUrl.replace("http", "ws")}/ws?clientId=${clientId}` ); this.ws.onopen = () => resolve(); this.ws.onerror = reject; this.ws.onmessage = (e) => this.handleMessage(e); }); } async handleMessage(event) { if (event.data instanceof Blob) { const buffer = await event.data.arrayBuffer(); const view = new DataView(buffer); const eventType = view.getUint32(0, false); if (eventType === 100) { const json = JSON.parse(new TextDecoder().decode(buffer.slice(4))); this.emit("progress", json); } else if (eventType === 101) { const metaLen = view.getUint32(4, false); const metadata = JSON.parse( new TextDecoder().decode(buffer.slice(8, 8 + metaLen)) ); const imageBlob = new Blob([buffer.slice(8 + metaLen)]); this.emit("preview", { url: URL.createObjectURL(imageBlob), metadata }); } } } on(event, handler) { this.handlers[event] = this.handlers[event] || []; this.handlers[event].push(handler); } emit(event, data) { (this.handlers[event] || []).forEach((h) => h(data)); } // List workflows async getWorkflows() { const res = await fetch(`${this.baseUrl}/imagelab/workflows`); return (await res.json()).workflows; } // Get workflow parameters with resolved options async getParameters(workflowId) { const res = await fetch( `${this.baseUrl}/imagelab/workflow/${workflowId}/parameters` ); return (await res.json()).parameters; } // Execute workflow async execute(workflowId, params) { const res = await fetch(`${this.baseUrl}/imagelab/workflow/${workflowId}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(params), }); return await res.json(); } // Get resources async getResources() { const res = await fetch(`${this.baseUrl}/imagelab/resources`); return (await res.json()).resources; } } // Usage const api = new ImageLabAPI(); await api.connect(); api.on("progress", (data) => { progressBar.style.width = `${data.progress_percent}%`; }); api.on("preview", ({ url }) => { previewImg.src = url; }); const result = await api.execute("basic_sdxl", { prompt: "a beautiful mountain landscape", negativePrompt: "blurry", checkpoints: ["dreamshaper_8.safetensors"], seed: 42, steps: 20, width: 1024, height: 1024, cfg: 8.0, }); console.log("Queued:", result.result.prompt_id); ``` ### Cancel Execution ```javascript // Cancel current execution await fetch("http://localhost:8188/interrupt", { method: "POST" }); // Cancel specific prompt await fetch("http://localhost:8188/interrupt", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt_id: "abc123" }), }); ``` ### Clear Queue ```javascript await fetch("http://localhost:8188/queue", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ clear: true }), }); ``` --- ## Dependencies | Package | Required | Purpose | | ---------- | -------- | ----------------------------------- | | `pydantic` | Yes | Parameter validation | | `pyyaml` | Yes | YAML schema files | | `watchdog` | Optional | Watch mode (`pip install watchdog`) | --- ## Troubleshooting ### Common Issues | Issue | Solution | | --------------------- | ----------------------------------------------------------- | | Workflow not found | Ensure `WORKFLOW_METADATA` and `run_workflow()` are defined | | Schema not generating | Check `WorkflowParams` is a valid Pydantic model | | Options not resolving | Verify `options_source` matches a valid resource type | | WebSocket no events | Ensure `add_progress_hook()` is called in `__init__.py` | | Watch mode error | Install watchdog: `pip install watchdog` | ### Logs Check ComfyUI console for `[ImageLab]` prefixed messages: ``` [ImageLab] progress patch applied successfully [ImageLab] routes registered successfully [ImageLab] Starting background indexing of new models... [workflows] Discovered: basic_sdxl - Basic SDXL Text to Image ``` --- **End of Documentation**