This repository has been archived on 2026-10-21. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
imagelab_v3_extension/DOCUMENTATION.md
T

26 KiB

ImageLab External API Documentation

Version: 2.1
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
  2. Directory Structure
  3. Quick Start
  4. API Endpoints
  5. WebSocket Events
  6. Workflow System
  7. YAML Schema System
  8. Resource System
  9. CLI Commands
  10. 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 with type/component separation
  • 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

Schema Design

The YAML schema separates concerns:

  • type: Data type (int, float, str, bool, enum, object)
  • component: Optional UI component hint (seed, prompt, sampler, etc.)

This allows the frontend to use generic components based on type while supporting custom UI for specific fields.

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

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

curl http://localhost:8188/imagelab/workflows

Get Workflow Parameters

curl http://localhost:8188/imagelab/workflow/basic_sdxl/parameters

API Endpoints

Workflow Endpoints

GET /imagelab/workflows

List all available workflows with metadata.

Response:

{
  "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:

{
  "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:

{
  "success": true,
  "workflow": "basic_sdxl",
  "parameters": [
    {
      "name": "prompt",
      "type": "str",
      "component": "prompt",
      "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",
      "component": "sampler",
      "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
        }
      ]
    },
    {
      "name": "seed",
      "type": "int",
      "component": "seed",
      "category": "parameters",
      "required": true,
      "label": "Seed"
    },
    {
      "name": "loras",
      "type": "object",
      "multiple": true,
      "component": "loras",
      "options_source": "loras",
      "category": "models",
      "default": [],
      "label": "Loras",
      "params": [
        { "name": "strength_model", "type": "float", "default": 1.0 },
        { "name": "strength_clip", "type": "float", "default": 1.0 }
      ]
    }
  ]
}

POST /imagelab/workflow/{workflow_name}

Execute a workflow with parameters.

Request:

{
  "prompt": "a beautiful sunset",
  "negativePrompt": "blurry",
  "checkpoints": ["model.safetensors"],
  "seed": 42,
  "steps": 20,
  "width": 1024,
  "height": 1024,
  "cfg": 8.0
}

Response:

{
  "success": true,
  "workflow": "basic_sdxl",
  "result": {
    "prompt_id": "abc123-def456-...",
    "status": "queued",
    "parameters": { ... }
  }
}

Error Response:

{
  "success": false,
  "type": "ValueError",
  "error": "Missing required fields: prompt, seed"
}

Resource Endpoints

GET /imagelab/resources

Get all available resources (models, samplers, schedulers).

Response:

{
  "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:

{
  "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:

{
  "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:

{
  "success": true,
  "message": "Indexing complete",
  "indexed": {
    "checkpoints": 3,
    "loras": 12
  }
}

WebSocket Events

Connection

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]

{
  "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]

{
  "node_id": "3",
  "prompt_id": "abc123"
}

Event 102: Workflow Event

Format: [4 bytes: event type][JSON payload]

{
  "event": "executing",
  "data": { "node": "3", "prompt_id": "abc123" }
}

Event types: executing, execution_start, executed, execution_error, execution_cached

JavaScript WebSocket Client

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:
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()
  1. Generate the YAML schema:
python -m external-api generate my_workflow
  1. 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)

The component property specifies the UI component to render (optional). The type is inferred from the Python type and metadata.

from typing import Annotated, List
from pydantic import Field

# Text fields - component specifies custom UI
Prompt = Annotated[str, Field(
    json_schema_extra={"component": "prompt", "category": "prompts", "multiline": True, "rows": 4}
)]
# Generated: type: str, component: prompt

# Special types - int with custom UI component
Seed = Annotated[int, Field(
    json_schema_extra={"component": "seed", "category": "parameters"}
)]
# Generated: type: int, component: seed

# Enum types - options_source triggers type: enum
Sampler = Annotated[str, Field(
    json_schema_extra={"component": "sampler", "options_source": "samplers", "category": "parameters"}
)]
# Generated: type: enum, component: sampler, options_source: samplers

# Model selectors - multiple selection from options_source
Checkpoint = Annotated[List[str], Field(
    json_schema_extra={"component": "checkpoints", "options_source": "checkpoints", "category": "models"}
)]
# Generated: type: enum, multiple: true, component: checkpoints

# Dimension fields - no component = generic slider
Width = Annotated[int, Field(
    ge=64, le=2048, multiple_of=8,
    json_schema_extra={"component": "dimensions", "category": "composition"}
)]
# Generated: type: int, component: dimensions, min: 64, max: 2048, step: 8

Type Inference Rules

The type property represents the data type, inferred automatically:

Condition Inferred type
Has options_source enum
Has params (complex model) object
Python int int
Python float float
Python str (no options) str
Python bool bool
Python List[T] type of T + multiple: true

YAML Format

The schema separates data type (type) from UI component (component):

name: Basic SDXL Text to Image
description: Workflow with SDXL presets for quick iteration.
category: Image Generation
model_types:
  - SDXL

parameters:
  # Text field with custom component
  - name: prompt
    type: str # Data type
    component: prompt # UI component (optional)
    category: prompts
    multiline: true
    required: true
    label: Your Creative Prompt
    rows: 4
    placeholder: Describe your image...

  # Seed - int with custom component
  - name: seed
    type: int # Data type
    component: seed # Custom UI component
    category: parameters
    required: true
    label: Seed

  # Enum - selection from options_source
  - name: sampler
    type: enum # Selection type (has options_source)
    component: sampler # UI component (optional)
    options_source: samplers
    category: parameters
    default: euler
    label: Sampler
    searchable: true

  # Multiple selection
  - name: checkpoints
    type: enum
    multiple: true # List[str] -> multiple selections
    component: checkpoints
    options_source: checkpoints
    category: models
    required: true
    label: Checkpoints

  # Complex type with params
  - name: loras
    type: object # Complex type (has params)
    multiple: true
    component: loras
    options_source: loras
    category: models
    default: []
    label: Loras
    params:
      - name: strength_model
        type: float
        default: 1.0
      - name: strength_clip
        type: float
        default: 1.0

  # Plain int with constraints (no custom component)
  - name: steps
    type: int
    category: parameters
    min: 1
    max: 150
    default: 20
    label: Steps
    # No component = frontend uses generic SliderField

  # Dimensions with custom component
  - name: width
    type: int
    component: dimensions
    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, component, default, required
  • min, max, step
  • category, options_source
  • multiple, params, multiline

Data Types (type)

The type property represents the semantic data type:

Type Description Properties
str Text/string multiline, rows
int Integer min, max, step
float Decimal min, max, step
bool Boolean toggle -
enum Selection from list options_source, searchable
object Complex with parameters options_source, params

UI Components (component)

The component property is an optional UI hint for custom rendering:

Component Description
prompt Multi-line text area for prompts
negative_prompt Multi-line text area for negative prompts
seed Seed input with randomize button
sampler Sampler dropdown with search
scheduler Scheduler dropdown
checkpoints Model multi-select with metadata
loras LoRA selector with strength sliders
dimensions Width/Height linked inputs

Component Resolution (Frontend):

Priority Check Example
1 component property component: "seed" → SeedField
2 options_source property options_source: "samplers" → SelectField
3 type + constraints type: "int" + min/max → SliderField
4 type only type: "bool" → ToggleField

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:

# 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:

# 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:

# __init__.py
AUTO_INDEX_ON_STARTUP = True

CLI Commands

The CLI is used for managing YAML workflow schemas.

# 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:

$ 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

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

// 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

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