A comprehensive SDK designed to simplify interaction with the FlowScale ComfyUI API. This library works in both Node.js and browser environments.
When using this SDK in a browser environment, your API key will be exposed to end users. This is a significant security risk. We strongly recommend:
- Using this SDK in a Node.js backend environment
- Creating a proxy API that securely handles the API key server-side
If you understand the risks and still need to use the SDK directly in the browser, you must explicitly acknowledge this by setting the allowDangerouslyExposeApiKey
option:
const flowscale = new FlowscaleAPI({
apiKey: 'your-api-key',
baseUrl: 'your-api-url',
allowDangerouslyExposeApiKey: false // Only set to true if you understand the security risks
});
Install the Flowscale SDK by npm
, yarn
, pnpm
or bun
:
npm install flowscale
yarn add flowscale
pnpm install flowscale
bun install flowscale
To get started, import the Flowscale SDK into your project:
import { FlowscaleAPI } from 'flowscale';
// Node.js Environment (Recommended)
const apiKey = process.env.FLOWSCALE_API_KEY;
const apiUrl = process.env.FLOWSCALE_API_URL;
const flowscale = new FlowscaleAPI({
apiKey,
baseUrl: apiUrl
});
// Browser Environment (Not Recommended)
const flowscale = new FlowscaleAPI({
apiKey: 'your-api-key', // ⚠️ WARNING: This will be exposed to users
baseUrl: 'https://your-api-url.pod.flowscale.ai',
allowDangerouslyExposeApiKey: true // Explicitly acknowledge the security risk
});
- Store API keys in environment variables
- Use
.env
files for configuration - Full access to all SDK features
- API key will be visible in network requests
- Supports File/Blob uploads directly from browser
- Consider implementing a backend proxy instead
Environment Variables: Add the following to your .env
file:
FLOWSCALE_API_KEY=your-api-key
FLOWSCALE_API_URL=https://your-api-url.pod.flowscale.ai
Below is a detailed guide to the SDK methods, including descriptions, usage, and response formats.
Description: Check the health status of the Flowscale platform, including the status of containers and services.
Usage:
const health = await flowscale.checkHealth();
console.log('API Health:', health);
Response Example:
{
"status": "success",
"data": [
{
"container": "container #1",
"status": "idle"
},
{
"container": "container #2",
"status": "running"
}
]
}
Description: Retrieve the current status of the workflow queue, including running and pending jobs.
Usage:
const queue = await flowscale.getQueue();
console.log('Queue Details:', queue);
Response Example:
{
"status": "success",
"data": [
{
"container": "container #1",
"queue": {
"queue_running": [
[
0,
"2a0babc4-acce-4521-9576-00fa0e6ecc91"
]
],
"queue_pending": [
[
1,
"5d60718a-7e89-4c64-b32d-0d1366b44e2a"
]
]
}
}
]
}
Description: Retrieves the list of all deployed workflows available in the cluster.
Usage:
const workflows = await flowscale.getWorkflows();
console.log('Available Workflows:', workflows);
Response Example:
{
"status": "success",
"data": [
{
"id": "bncu0a1kipv",
"name": "Text to Image",
"description": "Generate an image from text input",
"inputs": "{ \"text_51536\": \"string\" }",
"outputs": "{ \"image_output\": \"image\" }"
},
{
"id": "a9bc45rt2kpm",
"name": "Image to Image",
"description": "Transform an existing image",
"inputs": "{ \"image_input\": \"image\", \"prompt\": \"string\" }",
"outputs": "{ \"transformed_image\": \"image\" }"
}
]
}
Description:
Trigger a workflow execution using its unique workflowId
. Input data and an optional groupId
can be provided for better organization and tracking.
Parameters:
-
workflowId
(string): The unique ID of the workflow. -
data
(object): Input parameters for the workflow. -
groupId
(string, optional): A custom identifier for grouping runs.
Usage:
const workflowId = "bncu0a1kipv";
const groupId = "test_group";
const inputs = {
"text_51536": "Prompt test",
"image_1234": { /* File or Blob of image */ },
"video_1239": { /* File or Blob of video */ }
};
const result = await flowscale.executeWorkflow(workflowId, inputs, groupId);
console.log('Workflow Result:', result);
Response Example:
{
"status": "success",
"data": {
"number": 0,
"node_errors": {},
"output_names": [
"filename_prefix_58358_5WWF7GQUYF"
],
"run_id": "808f34d0-ef97-4b78-a00f-1268077ea6db"
}
}
Description:
Execute a workflow and automatically wait for the result by polling the output. This is a convenience method that combines executeWorkflow
and getOutput
with automatic polling.
Parameters:
-
workflowId
(string): The unique ID of the workflow. -
data
(object): Input parameters for the workflow. -
groupId
(string, optional): A custom identifier for grouping runs. -
pollIntervalMs
(number, optional): Polling interval in milliseconds (default: 1000). -
timeoutMs
(number, optional): Maximum time to wait for results in milliseconds (default: 300000 - 5 minutes).
Usage:
const workflowId = "bncu0a1kipv";
const inputs = {
"text_51536": "Prompt test",
"image_1234": { /* File or Blob of image */ }
};
try {
const result = await flowscale.executeWorkflowAsync(workflowId, inputs);
console.log('Workflow Result:', result);
} catch (error) {
if (error.message.includes('timed out')) {
console.error('Workflow took too long to complete');
} else {
console.error('Workflow error:', error);
}
}
Response Example:
{
"status": "success",
"data": {
"download_url": "https://runs.s3.amazonaws.com/generations/...",
"generation_status": "success"
}
}
Description:
Fetch the output of a completed workflow using its filename
. Outputs typically include downloadable files or results.
Parameters:
-
filename
(string): The name of the output file.
Usage:
const output = await flowscale.getOutput('filename_prefix_58358_5WWF7GQUYF.png');
console.log('Workflow Output:', output);
Response Example:
{
"status": "success",
"data": {
"download_url": "https://runs.s3.amazonaws.com/generations/...",
"generation_status": "success"
}
}
Description:
Cancel a running workflow execution using its unique runId
.
Parameters:
-
runId
(string): The unique identifier of the running workflow.
Usage:
const result = await flowscale.cancelRun('808f34d0-ef97-4b78-a00f-1268077ea6db');
console.log('Cancellation Result:', result);
Response Example:
{
"status": "success",
"data": "Run cancelled successfully"
}
Description: Retrieve detailed information about a specific workflow run.
Parameters:
-
runId
(string): The unique identifier of the run.
Usage:
const runDetails = await flowscale.getRun('808f34d0-ef97-4b78-a00f-1268077ea6db');
console.log('Run Details:', runDetails);
Response Example:
{
"status": "success",
"data": {
"_id": "808f34d0-ef97-4b78-a00f-1268077ea6db",
"status": "completed",
"inputs": [
{
"path": "text_51536",
"value": "a man riding a bike"
}
],
"outputs": [
{
"filename": "filename_prefix_58358_5WWF7GQUYF.png",
"url": "https://runs.s3.amazonaws.com/generations/..."
}
]
}
}
Description:
Retrieve all workflow runs associated with a specific groupId
. If no groupId
is provided, all runs for the team are returned.
Parameters:
-
groupId
(string, optional): The identifier for grouping runs.
Usage:
const runs = await flowscale.getRuns('test_group');
console.log('Runs for Group:', runs);
// Get all runs for the team
const allRuns = await flowscale.getRuns();
console.log('All Runs:', allRuns);
Response Example:
{
"status": "success",
"data": {
"group_id": "test_group",
"count": 2,
"runs": [
{
"_id": "cc29a72d-75b9-4c7b-b991-ccaf2a04d6ea",
"status": "completed",
"outputs": [
{
"filename": "filename_prefix_58358_G3DRLIVVYP.png",
"url": "https://runs.s3.amazonaws.com/generations/..."
}
]
}
]
}
}
- Always store sensitive information such as API keys in environment variables.
- Use
.env
files and libraries likedotenv
for easy environment management.
The SDK includes configurable logging to help with debugging and monitoring. By default, logging is enabled with the 'info' level.
const flowscale = new FlowscaleAPI({
apiKey: 'your-api-key',
baseUrl: 'https://your-api-url.pod.flowscale.ai',
enableLogging: true, // Enable/disable logging (default: true)
logLevel: 'info' // Set log level: 'debug', 'info', 'warn', 'error' (default: 'info')
});
You can also change logging settings after initialization:
// Enable debug logging
flowscale.setLoggingConfig(true, 'debug');
// Disable logging completely
flowscale.setLoggingConfig(false);
// Check current logging configuration
const loggingConfig = flowscale.getLoggingConfig();
console.log(loggingConfig); // { enabled: true, level: 'debug' }
- debug: Most verbose, includes detailed operation information
- info: General information about operations (default)
- warn: Warning messages for potential issues
- error: Only error messages
All logs are prefixed with timestamp and level:
[Flowscale INFO] 2025-06-03T10:30:45.123Z: WebSocket connection established
[Flowscale DEBUG] 2025-06-03T10:30:46.456Z: Polling workflow output: {...}
- Wrap API calls in try-catch blocks to handle errors gracefully.
- Log errors for debugging and improve resilience.
- Test workflows in a development environment before deploying to production.
- Validate inputs to ensure they match the workflow requirements.
The Flowscale SDK provides WebSocket functionality to enable real-time communication with the Flowscale API. This is particularly useful for receiving updates about workflow execution status and other events in real-time.
Description: Establishes a WebSocket connection to the Flowscale API.
Parameters:
-
options
(object, optional): Configuration options for the WebSocket connection.-
onOpen
(function, optional): Callback function executed when the connection opens. -
onClose
(function, optional): Callback function executed when the connection closes. -
onError
(function, optional): Callback function executed when an error occurs. -
onMessage
(function, optional): Callback function executed when a message is received. -
reconnect
(boolean, optional): Whether to attempt reconnection if the connection is lost. Default:true
. -
reconnectInterval
(number, optional): Milliseconds to wait before attempting to reconnect. Default:5000
. -
maxReconnectAttempts
(number, optional): Maximum number of reconnection attempts. Default:5
.
-
Usage:
// Connect to WebSocket and set up event handlers
const disconnect = flowscale.connectWebSocket({
onOpen: () => {
console.log('WebSocket connected!');
},
onMessage: (message) => {
console.log('Received message:', message);
// Handle different message types
if (message.type === 'run_status_update') {
console.log('Run status updated:', message.data);
}
},
onClose: (event) => {
console.log('WebSocket closed:', event.code, event.reason);
},
onError: (error) => {
console.error('WebSocket error:', error);
}
});
// Later, to disconnect:
disconnect();
Description: Closes the WebSocket connection if it is open.
Usage:
flowscale.disconnectWebSocket();
console.log('WebSocket disconnected');
Description: Sends a message through the WebSocket connection.
Parameters:
-
message
(any): The message to send. Objects will be automatically stringified.
Returns:
-
(boolean):
true
if the message was sent successfully,false
otherwise.
Usage:
const success = flowscale.sendWebSocketMessage({
type: 'client_event',
data: {
action: 'subscribe',
runId: '808f34d0-ef97-4b78-a00f-1268077ea6db'
}
});
if (success) {
console.log('Message sent successfully');
} else {
console.error('Failed to send message');
}
Description: Checks if the WebSocket connection is currently open.
Returns:
-
(boolean):
true
if the WebSocket is connected,false
otherwise.
Usage:
if (flowscale.isWebSocketConnected()) {
console.log('WebSocket is connected');
} else {
console.log('WebSocket is not connected');
}
The SDK includes example implementations for both browser and Node.js environments:
See examples/websocket-example.html
for a complete browser example with a user interface.
Node.js requires a custom WebSocket implementation since the WebSocket API is not built-in. See examples/node-websocket-example.js
for an example using the 'ws' library.
Note: To use WebSockets in Node.js, you'll need to install the 'ws' package:
npm install ws
Note: WebSocket functionality is natively available only in browser environments. For Node.js, you need to use a WebSocket library like ws
.
For any questions or assistance, join the Flowscale community on Discord or refer to the Flowscale Documentation.
Simplify your workflow management with the Flowscale Node.js SDK. Happy coding!