Skip to content

DaniilVdovin/ComfySharpSDK

Repository files navigation

en ru

ComfySharpSDK

ComfySharpSDK is a lightweight C# SDK for interacting with ComfyUI, a popular graphical interface for generating images using Stable Diffusion models. The library allows you to programmatically run workflows, track progress, and receive generated images directly in your .The NET application.

🚀 Quick Start

Did you like it? Put a star on it.

1. Launch ComfyUI

Make sure that your ComfyUI instance is running and accessible via HTTP (by default http://127.0.0.1:8188 ).
If you are using an API key (for example, when running with the --listen --enable-cors-header --extra-model-paths-config flag, etc.), specify it when creating the client.

2. Usage example

var client = new ComfyClient("http://192.168.0.10:8000");
var workflow = Workflow.LoadFromFile(Environment.CurrentDirectory + "\\Workflows\\Default.json");
workflow.SetNodeValue("6", "text", "Green Cat");
var images = await client.RunWorkflowAndGetImagesAsync(workflow,
(string message) => Console.WriteLine($"[PROGRESS] {message}")
);
foreach (var image in images)
{
if (image.Data == null || image.Filename == null) continue;
if (!Directory.Exists("Outputs")) Directory.CreateDirectory("Outputs");
await File.WriteAllBytesAsync(Path.Combine("Outputs",image.Filename), image.Data);
Console.WriteLine($"Image saved as {image.Filename}");
}


🧩 Main components

ComfyClient

The main client for interacting with ComfyUI.

Constructors

Basic constructor

public ComfyClient(string baseUrl = "http://127.0.0.1:8000", string? apiKey = null, int maxAttempts = 120)

Constructor with custom HttpClient (for DI or setting timeouts)

public ComfyClient(string baseUrl, HttpClient httpClient)

  • baseUrl is the ComfyUI server address (without the ending /).
  • apiKey is an optional Bearer token for authorization (if ComfyUI is protected).
  • maxAttempts — the maximum number of attempts to wait for a result (120 by default, i.e. ~2 minutes with a delay of 1 sec).

Methods

Method Description
RunWorkflowAsync(Workflow) Sends workflow to ComfyUI and returns `prompt_id'.
GetHistoryAsync(string promptId) Gets the execution history by `prompt_id'.
RunWorkflowAndGetImagesAsync(...) Full cycle: start → wait → load images.

Workflow

Represents the ComfyUI workflow in JSON format.

Creation

// From a JSON string
var workflow = Workflow.Load(jsonString);

// From the file
var workflow = Workflow.LoadFromFile("path/to/workflow.json");

Setting up the parameters

Native way
workflow.SetNodeValue("6", "text", "a dog in space");

Important: node_id is a string identifier of the node in the workflow JSON structure (for example, "6").

The names of inputs (input_name) depend on the node type (for example, "text", "seed", "steps", etc.).

Fluent

You can freely change the node parameters by specifying the key and value for them

workflow
.SetNodeValue("6", "text", "Green Cat")
.WithNodeByTitle("Positive Prompt", inp => inp["text"] = "Green Cat")
.WithNodeByClassType("CLIPTextEncode", inp => inp["text"] = "Green Cat");
workflow.WithNodeByClassType("KSampler", inp =>
{
inp["seed"] = 156680208700286;
inp["steps"] = 28;
inp["cfg"] = 7.5f;
inp["sampler_name"] = "euler";
inp["scheduler"] = "normal";
inp["denoise"] = 1;
});

DSL

This is a more elegant way, but it also requires specifying the key and value types

workflow.KSampler()
.Set("steps", 30)
.Set("seed", 12345)
.Set(new {
cfg = 7.5f,
denoise = 0.9f
});
workflow.ForNode(6)
.Set(new {
text = "Cat"
});

Dynamic Dsl

The most advanced way to edit a Workflow, the disadvantages are the need to download information about all nodes from ComfyUI, after which the system automatically collects objects from them

dynamic sampler = await workflow.ForNodeAsync("KSampler", client);
sampler
.Steps(30)
.Cfg(7.5)
.SamplerName("euler")
.Scheduler("Kerras");
await workflow.SetNodeAsync("KSampler", client, b =>
{
b.Steps(30).Cfg(7.5).SamplerName("euler");
});
await workflow.SetNodeAsync(6, client, b =>
{
b.Text("Pen Cat");
});

Additional information

  • GetNodes() — returns the dictionary Node ID → name (if specified in _meta.title).
  • toJSON() — serializes workflow back to readable JSON.

GeneratedImage

A class representing the generated image.

Property Description
NodeId ID of the node that generated the image
Filename File name (for example, "ComfyUI_00001_.png")
Subfolder Subfolder (if used)
Type Output type (usually "output")
Data Bytes of the image (byte[])

Authorization

If your ComfyUI is running with an API key (for example, via `--api-key your_secret_key'), pass it when creating the client.:

var client = new ComfyClient(
    baseUrl: "http://your-server.com:8188",
    apiKey: "your_secret_key"
);

The client will automatically add the header:


Authorization: Bearer your_secret_key


⏱️ Timeouts and cancellations

The RunWorkflowAndGetImagesAsync method supports the CancellationToken, which allows you to cancel the wait correctly.:

var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
var images = await client.RunWorkflowAndGetImagesAsync(workflow, cancellationToken: cts.Token);

If the result does not appear in maxAttempts (by default, 120 attempts × 1 sec = 2 min), a TimeoutException will be thrown.


📁 Workflow structure

ComfyUI expects workflow in JSON format, where each node has a unique string ID and inputs (inputs). Example of a node:

{
  "6": {
    "_meta": { "title": "CLIP Text Encode" },
    "class_type": "CLIPTextEncode",
    "inputs": {
      "text": "a cat",
      "clip": ["4", 1]
    }
  }
}

You can change the "text" via:

workflow.SetNodeValue("6", "text", "a dog in space");

🛠 Tips

  • Make sure that ComfyUI is running with the --listen flag if you are not using localhost.
  • For CORS requests, --enable-cors-header may be required.
  • Use Workflow.GetNodes() for debugging — it will show all available nodes and their names.
  • Images are stored temporarily on the ComfyUI server. Do not delay the download for a long time.

📜 License

MIT License — use it freely in personal and commercial projects.


Note: ComfySharpSDK is not an official ComfyUI product. This is a community-driven SDK.

About

A simple C# client for ComfyUI. With Workflow Runner

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages