@happyvertical/comfyui

中文文档
0.113.1发布于 2026/11/17MITTypeScriptES Module近 30 天下载 5350

ComfyUI API client for workflow orchestration and video generation

原始使用文档
文档目录19 节
  1. id: comfyui title: "@happyvertical/comfyui: ComfyUI API Cli…
  2. Overview
  3. Features
  4. Installation
  5. Quick Start
  6. Basic Usage
  7. Progress Tracking
  8. File Upload
  9. System Status
  10. API Reference
  11. ComfyUIClient
  12. injectWorkflowParams
  13. Types
  14. Errors
  15. Use Cases
  16. AI Video Generation Pipeline
  17. Batch Image Generation
  18. Requirements
  19. License

id: comfyui title: "@happyvertical/comfyui: ComfyUI API Client" sidebar_label: "@happyvertical/comfyui" sidebar_position: 10

@happyvertical/comfyui

License: MIT

A WebSocket-based client for ComfyUI workflow orchestration and video generation in the HAVE SDK.

Overview

The @happyvertical/comfyui package provides a TypeScript client for interacting with ComfyUI servers via WebSocket. It supports workflow execution, progress monitoring, and output downloading for AI-powered image and video generation pipelines.

Features

  • WebSocket Connection: Real-time communication with ComfyUI servers
  • Workflow Execution: Queue and execute ComfyUI workflows
  • Progress Monitoring: Track execution progress with detailed events
  • Parameter Injection: Dynamically inject values into workflow nodes
  • Output Download: Retrieve generated images and videos
  • Queue Management: Monitor and manage the execution queue
  • System Stats: Query server status and capabilities
  • File Upload: Upload images and other files for workflow inputs

Installation

# Install with bun (recommended)
bun add @happyvertical/comfyui

# Or with npm
npm install @happyvertical/comfyui

# Or with pnpm
pnpm add @happyvertical/comfyui

Quick Start

Basic Usage

import { ComfyUIClient, injectWorkflowParams } from '@happyvertical/comfyui';

// Create client
const client = new ComfyUIClient({
  url: 'http://localhost:8188',
});

// Connect to server
await client.connect();

// Load and modify workflow
const workflow = JSON.parse(fs.readFileSync('workflow.json', 'utf-8'));
const modifiedWorkflow = injectWorkflowParams(
  workflow,
  {
    seedImage: '3',
    prompt: '6',
  },
  {
    seedImage: 'input/anchor.png',
    prompt: 'professional news anchor speaking',
  }
);

// Queue prompt and wait for completion
const result = await client.queuePrompt(modifiedWorkflow);
const history = await client.waitForCompletion(result.promptId);

// Download output
const output = history.outputs['SaveVideo'];
if (output?.videos?.[0]) {
  const video = await client.downloadOutput(output.videos[0].filename);
  fs.writeFileSync('output.mp4', video);
}

await client.disconnect();

Progress Tracking

const history = await client.waitForCompletion(promptId, {
  onProgress: (event) => {
    switch (event.type) {
      case 'progress':
        console.log(`Progress: ${event.value}/${event.max}`);
        break;
      case 'executing':
        console.log(`Executing node: ${event.node}`);
        break;
      case 'execution_cached':
        console.log(`Cached nodes: ${event.nodes.join(', ')}`);
        break;
    }
  },
});

File Upload

// Upload image for workflow input
const imageBuffer = fs.readFileSync('input.png');
const uploadResult = await client.uploadImage(imageBuffer, 'input.png');

console.log(`Uploaded: ${uploadResult.name}`);

System Status

// Get system stats
const stats = await client.getSystemStats();
console.log(`Queue: ${stats.queue.running}/${stats.queue.pending}`);

// Get queue status
const queue = await client.getQueueStatus();
console.log(`Running: ${queue.running.length}, Pending: ${queue.pending.length}`);

API Reference

ComfyUIClient

The main client class for interacting with ComfyUI servers.

Constructor

new ComfyUIClient(options: ComfyUIClientOptions)
OptionTypeDefaultDescription
urlstring-ComfyUI server URL (e.g., http://localhost:8188)
clientIdstringauto-generatedUnique client identifier
timeoutnumber600000Request timeout in milliseconds

Methods

MethodDescription
connect()Establish WebSocket connection
disconnect()Close WebSocket connection
queuePrompt(workflow)Queue a workflow for execution
waitForCompletion(promptId, options?)Wait for prompt completion with progress tracking
getHistory(promptId)Get execution history for a prompt
getQueueStatus()Get current queue status
getSystemStats()Get server system statistics
uploadImage(buffer, filename, options?)Upload an image file
downloadOutput(filename, subfolder?, type?)Download a generated output file
interruptExecution()Interrupt the current execution
clearQueue()Clear all pending queue items

injectWorkflowParams

Utility function to inject dynamic values into workflow nodes.

function injectWorkflowParams(
  workflow: ComfyWorkflow,
  nodeMapping: NodeMapping,
  values: Record<string, unknown>
): ComfyWorkflow

Parameters

  • workflow - The ComfyUI workflow JSON
  • nodeMapping - Maps parameter names to node IDs (e.g., { seedImage: '3' })
  • values - Values to inject (e.g., { seedImage: 'path/to/image.png' })

Types

interface ComfyUIClientOptions {
  url: string;
  clientId?: string;
  timeout?: number;
}

interface PromptResult {
  promptId: string;
  number: number;
  nodeErrors?: Record<string, unknown>;
}

interface HistoryEntry {
  promptId: string;
  outputs: Record<string, NodeOutput>;
  status: { completed: boolean; messages?: unknown[] };
}

interface ProgressEvent {
  type: 'progress' | 'executing' | 'executed' | 'execution_cached' | 'execution_error';
  promptId?: string;
  node?: string;
  value?: number;
  max?: number;
  nodes?: string[];
}

Errors

A non-2xx response from ComfyUI throws ComfyUIRequestError (an ApiError from @happyvertical/utils). It carries status, method, path and the response body (parsed JSON, or the raw text). ComfyUI rejects a prompt that fails validation, such as a missing model file, with HTTP 400; the error then exposes the body's node_errors as nodeErrors and its error object as promptError. The message keeps the ComfyUI request failed: <status> <body> text.

import { ComfyUIRequestError } from '@happyvertical/comfyui';

try {
  await client.queuePrompt(workflow);
} catch (error) {
  if (error instanceof ComfyUIRequestError && error.nodeErrors) {
    console.error('Prompt rejected:', error.nodeErrors);
  }
  throw error;
}

Use Cases

AI Video Generation Pipeline

import { ComfyUIClient, injectWorkflowParams } from '@happyvertical/comfyui';

async function generateVideo(seedImage: string, audioFile: string) {
  const client = new ComfyUIClient({ url: 'http://localhost:8188' });
  await client.connect();

  try {
    // Upload inputs
    await client.uploadImage(fs.readFileSync(seedImage), 'seed.png');
    await client.uploadImage(fs.readFileSync(audioFile), 'audio.wav');

    // Load lip-sync workflow
    const workflow = JSON.parse(fs.readFileSync('lipsync-workflow.json', 'utf-8'));
    const modified = injectWorkflowParams(workflow, {
      seedImage: '3',
      audioFile: '5',
    }, {
      seedImage: 'input/seed.png',
      audioFile: 'input/audio.wav',
    });

    // Execute with progress
    const result = await client.queuePrompt(modified);
    const history = await client.waitForCompletion(result.promptId, {
      onProgress: (e) => {
        if (e.type === 'progress') {
          console.log(`Rendering: ${Math.round((e.value! / e.max!) * 100)}%`);
        }
      },
    });

    // Download output
    const output = history.outputs['SaveVideo'];
    return await client.downloadOutput(output.videos[0].filename);
  } finally {
    await client.disconnect();
  }
}

Batch Image Generation

async function generateBatch(prompts: string[]) {
  const client = new ComfyUIClient({ url: 'http://localhost:8188' });
  await client.connect();

  const results = [];
  for (const prompt of prompts) {
    const workflow = injectWorkflowParams(baseWorkflow, { prompt: '6' }, { prompt });
    const result = await client.queuePrompt(workflow);
    const history = await client.waitForCompletion(result.promptId);
    results.push(history);
  }

  await client.disconnect();
  return results;
}

Requirements

  • ComfyUI server running and accessible
  • Node.js 20+ or Bun
  • WebSocket support in runtime

License

This package is part of the HAVE SDK and is licensed under the MIT License - see the LICENSE file for details.

版本与发布记录

@happyvertical/comfyui 共发布 132 个版本,首次发布于 2026/06/23;过去 12 个月发布了 132 个版本。

版本发布日期距今
0.113.1latest2026/11/17今天
0.113.02026/11/152 天前
0.112.32026/11/134 天前
0.112.22026/11/125 天前
0.112.12026/11/125 天前
0.112.02026/11/125 天前

关于 @happyvertical/comfyui 的常见问题

@happyvertical/comfyui 是什么?

ComfyUI API client for workflow orchestration and video generation

如何安装 @happyvertical/comfyui?

在项目目录运行 npm install @happyvertical/comfyui,或使用 pnpm add / yarn add / bun add。

@happyvertical/comfyui 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@happyvertical/comfyui 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@happyvertical/comfyui 可以商用吗?

@happyvertical/comfyui 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@happyvertical/comfyui 的下载量有多少?

根据 npm 官方下载统计,@happyvertical/comfyui 在 2026/10/17 – 2026/11/15 这 30 天内被下载 5,350 次,日均约 178 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@happyvertical/comfyui 还在维护吗?

最新版本 0.113.1 发布于 2026/11/17(今天);至今共发布 132 个版本,其中过去 12 个月发布了 132 个;首次发布于 2026/06/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。