### Install Comfy2go Library Source: https://github.com/richinsley/comfy2go/blob/main/README.md Use 'go get' to install the latest version of the Comfy2go library. ```bash go get -u github.com/richinsley/comfy2go@latest ``` -------------------------------- ### Load Workflow from PNG and Queue Prompt Source: https://github.com/richinsley/comfy2go/blob/main/README.md This example demonstrates loading a ComfyUI workflow from a PNG file, initializing the ComfyGo client, and queuing the prompt to a ComfyUI instance. It then continuously monitors messages from the queued item, handling 'stopped' messages and downloading generated images. ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { clientaddr := "127.0.0.1" clientport := 8188 pngpath := "my_cool_workflow.png" // create a new ComgyGo client c := client.NewComfyClient(clientaddr, clientport, nil) // the ComgyGo client needs to be in an initialized state before // we can create and queue graphs if !c.IsInitialized() { log.Printf("Initialize Client with ID: %s\n", c.ClientID()) err := c.Init() if err != nil { log.Println("Error initializing client:", err) os.Exit(1) } } // create a graph from the png file graph, _, err := c.NewGraphFromPNGFile(pngpath) if err != nil { log.Println("Failed to get workflow graph from png file:", err) os.Exit(1) } // queue the prompt and get the resulting image item, err := c.QueuePrompt(graph) if err != nil { log.Println("Failed to queue prompt:", err) os.Exit(1) } // continuously read messages from the QueuedItem until we get the "stopped" message type for continueLoop := true; continueLoop; { msg := <-item.Messages switch msg.Type { case "stopped": // if we were stopped for an exception, display the exception message qm := msg.ToPromptMessageStopped() if qm.Exception != nil { log.Println(qm.Exception) os.Exit(1) } continueLoop = false case "data": qm := msg.ToPromptMessageData() // data objects have the fields: Filename, Subfolder, Type // * Subfolder is the subfolder in the output directory // * Type is the type of the image temp/ for k, v := range qm.Data { if k == "images" || k == "gifs" { for _, output := range v { img_data, err := c.GetImage(output) if err != nil { log.Println("Failed to get image:", err) os.Exit(1) } f, err := os.Create(output.Filename) if err != nil { log.Println("Failed to write image:", err) os.Exit(1) } f.Write(*img_data) f.Close() log.Println("Got image: ", output.Filename) } } } } } } ``` -------------------------------- ### Retrieve installed extensions Source: https://context7.com/richinsley/comfy2go/llms.txt Lists all extensions currently installed on the ComfyUI server. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) extensions, err := c.GetExtensions() if err != nil { log.Fatal(err) } log.Println("Installed Extensions:") for _, ext := range extensions { log.Printf(" - %s", ext) } } ``` -------------------------------- ### Get Prompt Execution History Source: https://context7.com/richinsley/comfy2go/llms.txt Fetches the prompt execution history, sorted by index. This is useful for reviewing past runs and their associated outputs. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) history, err := c.GetPromptHistoryByIndex() if err != nil { log.Fatal(err) } log.Println("Prompt History:") for _, item := range history { log.Printf("Index: %d, Prompt ID: %s", item.Index, item.PromptID) for nodeID, outputs := range item.Outputs { log.Printf(" Node %d outputs:", nodeID) for _, output := range outputs { log.Printf(" - %s (%s)", output.Filename, output.Type) } } } } ``` -------------------------------- ### Get Node Information Source: https://context7.com/richinsley/comfy2go/llms.txt Retrieves detailed information about all available node types, including their properties and input/output specifications. Useful for understanding ComfyUI's capabilities. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) nodeObjects, err := c.GetObjectInfos() if err != nil { log.Fatal(err) } log.Println("Available Nodes:") for _, node := range nodeObjects.Objects { log.Printf("Node: %s", node.DisplayName) props := node.GetSettableProperties() for _, prop := range props { log.Printf(" Property: %s (Type: %s)", prop.Name(), prop.TypeString()) if prop.TypeString() == "COMBO" { comboProp, _ := prop.ToComboProperty() for _, val := range comboProp.Values { log.Printf(" Option: %s", val) } } } } } ``` -------------------------------- ### Get Available Embedding Models Source: https://context7.com/richinsley/comfy2go/llms.txt Retrieves a list of available embedding models from the ComfyUI server. Ensure the client is initialized with the correct server address and port. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) embeddings, err := c.GetEmbeddings() if err != nil { log.Fatal(err) } log.Println("Available Embeddings:") for _, emb := range embeddings { log.Printf(" - %s", emb) } } ``` -------------------------------- ### Get Group and Nodes in ComfyUI Workflow Source: https://context7.com/richinsley/comfy2go/llms.txt Retrieves a specific group by its title and then lists all nodes contained within that group. Ensure the group title exists in your workflow. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("workflow.json") // Get a specific group by title group := graph.GetGroupWithTitle("Sampling") if group == nil { log.Fatal("Group 'Sampling' not found") } log.Printf("Group: %s", group.Title) // Get all nodes within the group nodesInGroup := graph.GetNodesInGroup(group) log.Printf("Nodes in group '%s':", group.Title) for _, node := range nodesInGroup { log.Printf(" - %s (ID: %d, Type: %s)", node.Title, node.ID, node.Type) } } ``` -------------------------------- ### Configure Node Properties Source: https://context7.com/richinsley/comfy2go/llms.txt Demonstrates how to retrieve and update INT, FLOAT, and COMBO properties on a node. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("workflow.json") // Find a KSampler node sampler := graph.GetFirstNodeWithTitle("KSampler") if sampler == nil { log.Fatal("KSampler not found") } // INT property - seed seedProp := sampler.GetPropertyWithName("seed") if seedProp != nil { intProp, ok := seedProp.ToIntProperty() if ok { log.Printf("Seed range: %d to %d", intProp.Min, intProp.Max) } seedProp.SetValue(12345) } // FLOAT property - cfg cfgProp := sampler.GetPropertyWithName("cfg") if cfgProp != nil { floatProp, ok := cfgProp.ToFloatProperty() if ok { log.Printf("CFG range: %.2f to %.2f", floatProp.Min, floatProp.Max) } cfgProp.SetValue(7.5) } // COMBO property - sampler_name samplerNameProp := sampler.GetPropertyWithName("sampler_name") if samplerNameProp != nil { comboProp, ok := samplerNameProp.ToComboProperty() if ok { log.Printf("Available samplers: %v", comboProp.Values) } samplerNameProp.SetValue("euler_ancestral") } // INT property - steps stepsProp := sampler.GetPropertyWithName("steps") if stepsProp != nil { stepsProp.SetValue(30) } log.Println("All properties configured successfully") } ``` -------------------------------- ### Queue and process with QueuePromptAndProcess Source: https://context7.com/richinsley/comfy2go/llms.txt Atomically queues a prompt and uses handler callbacks to process messages, preventing potential race conditions. ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("workflow.json") // Queue and process in one atomic operation err := c.QueuePromptAndProcess(graph, client.DefaultMessageHandlers(). WithProgressHandler(func(msg *client.PromptMessageProgress) { log.Printf("Progress: %d/%d", msg.Value, msg.Max) }). WithDataHandler(func(msg *client.PromptMessageData) { for k, outputs := range msg.Data { if k == "images" || k == "gifs" { for _, output := range outputs { imgData, _ := c.GetImage(output) os.WriteFile(output.Filename, *imgData, 0644) log.Printf("Saved: %s", output.Filename) } } } }). WithErrorHandler(func(err *client.PromptMessageStoppedException) { log.Printf("Error in node %s: %s", err.NodeID, err.ExceptionMessage) }), ) if err != nil { log.Fatal("Execution failed:", err) } log.Println("Execution completed successfully") } ``` -------------------------------- ### Create ComfyClient with Callbacks Source: https://context7.com/richinsley/comfy2go/llms.txt Initialize a ComfyClient to connect to a ComfyUI backend. Callbacks can be provided to monitor client events like queue changes and prompt status. ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { // Create callbacks for monitoring client events callbacks := &client.ComfyClientCallbacks{ ClientQueueCountChanged: func(c *client.ComfyClient, queuecount int) { log.Printf("Queue size changed: %d", queuecount) }, QueuedItemStarted: func(c *client.ComfyClient, qi *client.QueueItem) { log.Printf("Prompt %s started", qi.PromptID) }, QueuedItemStopped: func(cc *client.ComfyClient, qi *client.QueueItem, reason client.QueuedItemStoppedReason) { log.Printf("Prompt %s stopped with reason: %s", qi.PromptID, reason) }, QueuedItemDataAvailable: func(cc *client.ComfyClient, qi *client.QueueItem, pmd *client.PromptMessageData) { log.Printf("Data available for prompt %s", qi.PromptID) }, } // Create client with callbacks (callbacks can be nil) c := client.NewComfyClient("localhost", 8188, callbacks) // Initialize the client before use if !c.IsInitialized() { log.Printf("Initializing client with ID: %s", c.ClientID()) err := c.Init() if err != nil { log.Fatal("Error initializing client:", err) } } log.Println("Client initialized successfully") } ``` -------------------------------- ### Retrieve system statistics Source: https://context7.com/richinsley/comfy2go/llms.txt Fetches OS, Python, and GPU hardware details from the ComfyUI backend. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) stats, err := c.GetSystemStats() if err != nil { log.Fatal(err) } log.Printf("OS: %s", stats.System.OS) log.Printf("Python Version: %s", stats.System.PythonVersion) log.Printf("Embedded Python: %v", stats.System.EmbeddedPython) for _, device := range stats.Devices { log.Printf("GPU %d: %s", device.Index, device.Name) log.Printf(" Type: %s", device.Type) log.Printf(" VRAM Total: %d bytes", device.VRAM_Total) log.Printf(" VRAM Free: %d bytes", device.VRAM_Free) log.Printf(" Torch VRAM Total: %d bytes", device.Torch_VRAM_Total) log.Printf(" Torch VRAM Free: %d bytes", device.Torch_VRAM_Free) } } ``` -------------------------------- ### Queue a workflow with QueuePrompt Source: https://context7.com/richinsley/comfy2go/llms.txt Queues a workflow graph for execution and manually processes the resulting message stream. ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("workflow.json") // Queue the prompt for execution item, err := c.QueuePrompt(graph) if err != nil { log.Fatal("Failed to queue prompt:", err) } log.Printf("Queued prompt with ID: %s", item.PromptID) // Process messages from the queue item for continueLoop := true; continueLoop; { msg := <-item.Messages switch msg.Type { case "started": log.Println("Execution started") case "executing": execMsg := msg.ToPromptMessageExecuting() log.Printf("Executing node: %s (%s)", execMsg.NodeID, execMsg.Title) case "progress": progMsg := msg.ToPromptMessageProgress() log.Printf("Progress: %d/%d", progMsg.Value, progMsg.Max) case "data": dataMsg := msg.ToPromptMessageData() for k, outputs := range dataMsg.Data { if k == "images" { for _, output := range outputs { imgData, _ := c.GetImage(output) os.WriteFile(output.Filename, *imgData, 0644) log.Printf("Saved image: %s", output.Filename) } } } case "stopped": stopped := msg.ToPromptMessageStopped() if stopped.Exception != nil { log.Printf("Error: %s", stopped.Exception.ExceptionMessage) } continueLoop = false } } } ``` -------------------------------- ### Create ComfyClient with Timeout Source: https://context7.com/richinsley/comfy2go/llms.txt Establish a ComfyClient connection with custom timeout and retry settings, useful for unstable network conditions. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { // Create client with 30-second timeout timeout := 30000 // milliseconds retry := 3 c := client.NewComfyClientWithTimeout("192.168.1.100", 8188, nil, timeout, retry) err := c.Init() if err != nil { log.Fatal("Connection failed:", err) } log.Println("Connected with timeout settings") } ``` -------------------------------- ### Queue Prompt with Custom Message Handlers Source: https://context7.com/richinsley/comfy2go/llms.txt Queues a prompt for execution and processes responses using custom handlers for different event types (executing, progress, data, completion). Requires a running ComfyUI instance. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" "github.com/schollz/progressbar/v3" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("workflow.json") var bar *progressbar.ProgressBar err := c.QueuePromptAndProcess(graph, client.DefaultMessageHandlers(). WithExecutingHandler(func(msg *client.PromptMessageExecuting) { log.Printf("Executing: %s", msg.Title) }). WithProgressHandler(func(msg *client.PromptMessageProgress) { if bar == nil { bar = progressbar.Default(int64(msg.Max)) } bar.Set(msg.Value) }). WithDataHandler(func(msg *client.PromptMessageData) { for k, outputs := range msg.Data { log.Printf("Output type '%s': %d items", k, len(outputs)) } }). WithCompleteHandler(func() { log.Println("Processing complete!") }), ) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Upload Image and Bind to Node Source: https://context7.com/richinsley/comfy2go/llms.txt Uploads a generated image and binds it to a 'Load Image' node for workflow execution. ```go package main import ( "image" "image/color" "image/draw" "log" "math" "os" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("img2img_workflow.json") // Create a test image with rolling hills img := image.NewRGBA(image.Rect(0, 0, 512, 512)) skyColor := color.RGBA{135, 206, 250, 255} hillColor := color.RGBA{34, 139, 34, 255} draw.Draw(img, image.Rect(0, 0, 512, 256), &image.Uniform{skyColor}, image.Point{}, draw.Src) for x := 0; x < 512; x++ { y := 256 + int(50*math.Sin(float64(x)*0.02)) draw.Draw(img, image.Rect(x, y, x+1, 512), &image.Uniform{hillColor}, image.Point{}, draw.Src) } // Find Load Image node and get its upload property loadImageNode := graph.GetFirstNodeWithTitle("Load Image") if loadImageNode == nil { log.Fatal("Load Image node not found") } // Get the file upload property (may be "choose file to upload" or alias "file") prop := loadImageNode.GetPropertyWithName("choose file to upload") if prop == nil { prop = loadImageNode.GetPropertyWithName("file") } if prop != nil { uploadProp, ok := prop.ToImageUploadProperty() if ok { // Upload and automatically bind to the node filename, err := c.UploadImage(img, "input_hills.png", false, client.InputImageType, "", uploadProp) if err != nil { log.Fatal("Upload failed:", err) } log.Printf("Uploaded and bound image: %s", filename) } } // Execute the workflow item, _ := c.QueuePrompt(graph) err := item.ProcessMessages( client.DefaultMessageHandlers(). WithDataHandler(func(msg *client.PromptMessageData) { for k, outputs := range msg.Data { if k == "images" { for _, output := range outputs { imgData, _ := c.GetImage(output) os.WriteFile(output.Filename, *imgData, 0644) log.Printf("Saved output: %s", output.Filename) } } } }), ) if err != nil { log.Fatal("Execution failed:", err) } } ``` -------------------------------- ### Import Comfy2go APIs Source: https://github.com/richinsley/comfy2go/blob/main/README.md Include the Comfy2go client and optionally the graph APIs in your Go application. ```go import "github.com/richinsley/comfy2go/client" import "github.com/richinsley/comfy2go/graphapi" ``` -------------------------------- ### Load Graph from JSON File Source: https://context7.com/richinsley/comfy2go/llms.txt Load a ComfyUI workflow from a JSON file into a Graph object. Handles potential missing custom nodes. ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) if err := c.Init(); err != nil { log.Fatal(err) } // Load workflow from JSON file graph, missingNodes, err := c.NewGraphFromJsonFile("workflow.json") if err != nil { log.Fatal("Error loading workflow:", err) } // Check for missing custom nodes if missingNodes != nil && len(*missingNodes) > 0 { log.Printf("Warning: Missing nodes: %v", *missingNodes) } log.Printf("Loaded graph with %d nodes", len(graph.Nodes)) } ``` -------------------------------- ### Client API - NewComfyClient Source: https://context7.com/richinsley/comfy2go/llms.txt Creates a new ComfyClient instance to connect to a ComfyUI backend server. This client manages WebSocket connections, prompt queuing, and message handling. Callbacks can be provided to monitor client events. ```APIDOC ## NewComfyClient ### Description Creates a new ComfyClient instance that connects to a ComfyUI backend server. The client manages WebSocket connections, prompt queuing, and message handling. ### Method `client.NewComfyClient(host string, port int, callbacks *ComfyClientCallbacks) *ComfyClient` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { // Create callbacks for monitoring client events callbacks := &client.ComfyClientCallbacks{ ClientQueueCountChanged: func(c *client.ComfyClient, queuecount int) { log.Printf("Queue size changed: %d", queuecount) }, QueuedItemStarted: func(c *client.ComfyClient, qi *client.QueueItem) { log.Printf("Prompt %s started", qi.PromptID) }, QueuedItemStopped: func(cc *client.ComfyClient, qi *client.QueueItem, reason client.QueuedItemStoppedReason) { log.Printf("Prompt %s stopped with reason: %s", qi.PromptID, reason) }, QueuedItemDataAvailable: func(cc *client.ComfyClient, qi *client.QueueItem, pmd *client.PromptMessageData) { log.Printf("Data available for prompt %s", qi.PromptID) }, } // Create client with callbacks (callbacks can be nil) c := client.NewComfyClient("localhost", 8188, callbacks) // Initialize the client before use if !c.IsInitialized() { log.Printf("Initializing client with ID: %s", c.ClientID()) err := c.Init() if err != nil { log.Fatal("Error initializing client:", err) } } log.Println("Client initialized successfully") } ``` ### Response #### Success Response (200) None (This is a constructor function) #### Response Example None ``` -------------------------------- ### Upload File from Local Path Source: https://context7.com/richinsley/comfy2go/llms.txt Uploads a file from the local filesystem to the ComfyUI server. This method allows specifying whether to overwrite existing files and the destination type. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() // Upload existing file filename, err := c.UploadFileFromPath( "/path/to/image.png", true, // overwrite if exists client.InputImageType, // destination type: input, temp, or output "", // subfolder (empty for root) nil, // target property (optional) ) if err != nil { log.Fatal("Upload failed:", err) } log.Printf("File uploaded as: %s", filename) } ``` -------------------------------- ### Download Image from ComfyUI Source: https://context7.com/richinsley/comfy2go/llms.txt Downloads an image from the ComfyUI server using its output reference. The downloaded image data is then saved to a local file. ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() // DataOutput typically comes from prompt execution results output := client.DataOutput{ Filename: "ComfyUI_00001_.png", Subfolder: "", Type": "output", } imageData, err := c.GetImage(output) if err != nil { log.Fatal("Failed to get image:", err) } err = os.WriteFile("downloaded_image.png", *imageData, 0644) if err != nil { log.Fatal("Failed to save image:", err) } log.Println("Image downloaded successfully") } ``` -------------------------------- ### Client API - NewComfyClientWithTimeout Source: https://context7.com/richinsley/comfy2go/llms.txt Creates a new ComfyClient with a custom connection timeout and retry settings, useful for unreliable network conditions. ```APIDOC ## NewComfyClientWithTimeout ### Description Creates a new ComfyClient with a custom connection timeout for unreliable network conditions. ### Method `client.NewComfyClientWithTimeout(host string, port int, callbacks *ComfyClientCallbacks, timeout int, retry int) *ComfyClient` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { // Create client with 30-second timeout timeout := 30000 // milliseconds retry := 3 c := client.NewComfyClientWithTimeout("192.168.1.100", 8188, nil, timeout, retry) err := c.Init() if err != nil { log.Fatal("Connection failed:", err) } log.Println("Connected with timeout settings") } ``` ### Response #### Success Response (200) None (This is a constructor function) #### Response Example None ``` -------------------------------- ### Graph API - NewGraphFromJsonFile Source: https://context7.com/richinsley/comfy2go/llms.txt Loads a ComfyUI workflow from a JSON file and creates a Graph object, allowing for programmatic manipulation of the workflow. ```APIDOC ## NewGraphFromJsonFile ### Description Loads a ComfyUI workflow from a JSON file and creates a Graph object for manipulation. ### Method `c.NewGraphFromJsonFile(filePath string) (*Graph, *[]string, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) if err := c.Init(); err != nil { log.Fatal(err) } // Load workflow from JSON file graph, missingNodes, err := c.NewGraphFromJsonFile("workflow.json") if err != nil { log.Fatal("Error loading workflow:", err) } // Check for missing custom nodes if missingNodes != nil && len(*missingNodes) > 0 { log.Printf("Warning: Missing nodes: %v", *missingNodes) } log.Printf("Loaded graph with %d nodes", len(graph.Nodes)) } ``` ### Response #### Success Response (200) - **graph** (*Graph) - The loaded ComfyUI workflow graph. - **missingNodes** (*[]string) - A slice of strings indicating any missing custom nodes. #### Response Example None ``` -------------------------------- ### Upload Image to ComfyUI Source: https://context7.com/richinsley/comfy2go/llms.txt Uploads a generated or existing image to the ComfyUI server's input directory. The image is created in memory and then uploaded. ```go package main import ( "image" "image/color" "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() // Create a simple test image img := image.NewRGBA(image.Rect(0, 0, 512, 512)) for y := 0; y < 512; y++ { for x := 0; x < 512; x++ { img.Set(x, y, color.RGBA{uint8(x % 256), uint8(y % 256), 128, 255}) } } // Upload image to ComfyUI input folder filename, err := c.UploadImage(img, "test_image.png", true, client.InputImageType, "", nil) if err != nil { log.Fatal("Upload failed:", err) } log.Printf("Image uploaded as: %s", filename) } ``` -------------------------------- ### GetImage API Source: https://context7.com/richinsley/comfy2go/llms.txt Downloads an image from the ComfyUI server by its output data reference. ```APIDOC ## GetImage ### Description Downloads an image from the ComfyUI server by its output data reference. ### Method POST ### Endpoint /get/image ### Parameters #### Request Body - **output_data** (object) - Required - Reference to the image output. - **Filename** (string) - Required - The filename of the image. - **Subfolder** (string) - Optional - The subfolder where the image is located. - **Type** (string) - Required - The type of the output (e.g., "output", "input", "temp"). ### Request Example { "output_data": { "Filename": "ComfyUI_00001_.png", "Subfolder": "", "Type": "output" } } ### Response #### Success Response (200) - **image_data** (binary) - The binary data of the requested image. #### Response Example (Binary image data) ``` -------------------------------- ### GetPromptHistoryByIndex API Source: https://context7.com/richinsley/comfy2go/llms.txt Retrieves prompt execution history sorted by index. ```APIDOC ## GetPromptHistoryByIndex ### Description Retrieves prompt execution history sorted by index. ### Method GET ### Endpoint /prompt_history ### Parameters None ### Request Example None ### Response #### Success Response (200) - **history** (array[object]) - A list of prompt execution history items. - **Index** (integer) - The index of the prompt execution. - **PromptID** (string) - The unique identifier for the prompt. - **Outputs** (object) - A map of node IDs to their output details. - **nodeID** (string) - The ID of the node. - **Filename** (string) - The name of the output file. - **Type** (string) - The type of the output. #### Response Example { "history": [ { "Index": 1, "PromptID": "abc123xyz", "Outputs": { "0": [ { "Filename": "ComfyUI_00001_.png", "Type": "output" } ] } } ] } ``` -------------------------------- ### UploadFileFromPath API Source: https://context7.com/richinsley/comfy2go/llms.txt Uploads a file from the local filesystem to ComfyUI. ```APIDOC ## UploadFileFromPath ### Description Uploads a file from the local filesystem to ComfyUI. ### Method POST ### Endpoint /upload/file ### Parameters #### Query Parameters - **filename** (string) - Required - The desired filename for the uploaded file. - **overwrite** (boolean) - Optional - Whether to overwrite the file if it already exists. - **type** (string) - Required - The type of upload destination (e.g., "input", "temp", "output"). - **subfolder** (string) - Optional - The subfolder within the destination type to upload to. ### Request Body - **file_content** (binary) - Required - The binary content of the file to upload. ### Request Example (Binary file content) ### Response #### Success Response (200) - **name** (string) - The filename of the uploaded file on the server. #### Response Example { "name": "uploaded_file.png" } ``` -------------------------------- ### Graph API - NewGraphFromPNGFile Source: https://context7.com/richinsley/comfy2go/llms.txt Extracts workflow metadata embedded within a PNG file generated by ComfyUI, creating a Graph object for analysis or modification. ```APIDOC ## NewGraphFromPNGFile ### Description Extracts workflow metadata from a PNG file generated by ComfyUI and creates a Graph object. ### Method `c.NewGraphFromPNGFile(filePath string) (*Graph, *[]string, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) if err := c.Init(); err != nil { log.Fatal(err) } // Extract workflow from PNG metadata graph, missingNodes, err := c.NewGraphFromPNGFile("generated_image.png") if err != nil { log.Fatal("Error extracting workflow from PNG:", err) } if missingNodes != nil { log.Printf("Missing nodes: %v", *missingNodes) } log.Printf("Extracted workflow with %d nodes from PNG", len(graph.Nodes)) } ``` ### Response #### Success Response (200) - **graph** (*Graph) - The ComfyUI workflow graph extracted from the PNG. - **missingNodes** (*[]string) - A slice of strings indicating any missing custom nodes. #### Response Example None ``` -------------------------------- ### Modify Workflow Properties with SimpleAPI Source: https://context7.com/richinsley/comfy2go/llms.txt Creates a SimpleAPI interface from nodes within a named group in the workflow. This provides easy access to modify workflow parameters without navigating the full graph structure. Requires a 'workflow.json' file. ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("workflow.json") // Get SimpleAPI for nodes in the "API" group (default) simpleAPI := graph.GetSimpleAPI(nil) if simpleAPI == nil { log.Fatal("No 'API' group found in workflow") } // Set properties by node title if width := simpleAPI.Properties["Width"]; width != nil { width.SetValue(1024) } if height := simpleAPI.Properties["Height"]; height != nil { height.SetValue(1024) } if positive := simpleAPI.Properties["Positive"]; positive != nil { positive.SetValue("a beautiful sunset over mountains, highly detailed") } if negative := simpleAPI.Properties["Negative"]; negative != nil { negative.SetValue("blurry, low quality, watermark") } if seed := simpleAPI.Properties["Seed"]; seed != nil { seed.SetValue(42) } // Queue and execute item, _ := c.QueuePrompt(graph) for { msg := <-item.Messages if msg.Type == "stopped" { break } } } ``` -------------------------------- ### History Management Source: https://context7.com/richinsley/comfy2go/llms.txt Endpoints for clearing prompt history from the ComfyUI server. ```APIDOC ## EraseHistoryItem ### Description Removes a specific prompt history item from the server. ### Parameters #### Request Body - **prompt-uuid** (string) - Required - The unique identifier of the history item to remove. ## EraseHistory ### Description Clears all prompt history from the ComfyUI server. ``` -------------------------------- ### Extract Graph from PNG File Source: https://context7.com/richinsley/comfy2go/llms.txt Extract ComfyUI workflow data embedded within a PNG image file. Reports any missing custom nodes. ```go package main import ( "log" "os" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) if err := c.Init(); err != nil { log.Fatal(err) } // Extract workflow from PNG metadata graph, missingNodes, err := c.NewGraphFromPNGFile("generated_image.png") if err != nil { log.Fatal("Error extracting workflow from PNG:", err) } if missingNodes != nil { log.Printf("Missing nodes: %v", *missingNodes) } log.Printf("Extracted workflow with %d nodes from PNG", len(graph.Nodes)) } ``` -------------------------------- ### GetObjectInfos API Source: https://context7.com/richinsley/comfy2go/llms.txt Retrieves information about all available node types in ComfyUI, including their properties and inputs. ```APIDOC ## GetObjectInfos ### Description Retrieves information about all available node types in ComfyUI, including their properties and inputs. ### Method GET ### Endpoint /object_info ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Objects** (array[object]) - A list of node objects. - **DisplayName** (string) - The display name of the node. - **SettableProperties** (array[object]) - A list of settable properties for the node. - **Name** (string) - The name of the property. - **TypeString** (string) - The type of the property (e.g., "COMBO", "STRING"). - **Values** (array[string], optional) - Possible values if the type is "COMBO". #### Response Example { "Objects": [ { "DisplayName": "LoadImage", "SettableProperties": [ { "Name": "image", "TypeString": "IMAGE" }, { "Name": "upload", "TypeString": "COMBO", "Values": ["input", "temp", "output"] } ] } ] } ``` -------------------------------- ### Find Nodes by Type in ComfyUI Graph Source: https://context7.com/richinsley/comfy2go/llms.txt Retrieves all nodes of a specific type from the workflow graph, such as CheckpointLoaderSimple nodes. Allows iteration and modification of properties like checkpoint names. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("workflow.json") // Find all CheckpointLoaderSimple nodes loaderNodes := graph.GetNodesWithType("CheckpointLoaderSimple") for _, node := range loaderNodes { ckptProp := node.GetPropertyWithName("ckpt_name") if ckptProp != nil { comboProp, ok := ckptProp.ToComboProperty() if ok { log.Printf("Available checkpoints for node %d:", node.ID) for _, val := range comboProp.Values { log.Printf(" - %s", val) } // Set a specific checkpoint ckptProp.SetValue("sd_xl_base_1.0.safetensors") } } } } ``` -------------------------------- ### GetEmbeddings API Source: https://context7.com/richinsley/comfy2go/llms.txt Retrieves the list of available embedding models from the ComfyUI server. ```APIDOC ## GetEmbeddings ### Description Retrieves the list of available embedding models from the ComfyUI server. ### Method GET ### Endpoint /embeddings ### Parameters None ### Request Example None ### Response #### Success Response (200) - **embeddings** (array[string]) - A list of available embedding model names. #### Response Example { "embeddings": [ "model1.pt", "model2.safetensors" ] } ``` -------------------------------- ### Interrupt API Source: https://context7.com/richinsley/comfy2go/llms.txt Interrupts the currently executing prompt on the ComfyUI server. ```APIDOC ## Interrupt ### Description Interrupts the currently executing prompt on the ComfyUI server. ### Method POST ### Endpoint /interrupt ### Parameters None ### Request Example None ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the interruption. #### Response Example { "message": "Execution interrupted" } ``` -------------------------------- ### UploadImage API Source: https://context7.com/richinsley/comfy2go/llms.txt Uploads an image to the ComfyUI server for use in workflows. ```APIDOC ## UploadImage ### Description Uploads an image to the ComfyUI server for use in workflows. ### Method POST ### Endpoint /upload/image ### Parameters #### Query Parameters - **filename** (string) - Required - The desired filename for the uploaded image. - **overwrite** (boolean) - Optional - Whether to overwrite the file if it already exists. - **type** (string) - Required - The type of upload destination (e.g., "input", "temp", "output"). - **subfolder** (string) - Optional - The subfolder within the destination type to upload to. ### Request Body - **image_data** (binary) - Required - The binary data of the image file. ### Request Example (Binary image data) ### Response #### Success Response (200) - **name** (string) - The filename of the uploaded image on the server. #### Response Example { "name": "test_image.png" } ``` -------------------------------- ### Retrieve Node by ID Source: https://context7.com/richinsley/comfy2go/llms.txt Access a specific node within a loaded graph using its unique identifier. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("workflow.json") // Get node by ID node := graph.GetNodeById(5) if node != nil { log.Printf("Node %d: %s (%s)", node.ID, node.Title, node.Type) log.Printf(" Display Name: %s", node.DisplayName) log.Printf(" Is Output Node: %v", node.IsOutput) } } ``` -------------------------------- ### Graph API Source: https://context7.com/richinsley/comfy2go/llms.txt Methods for interacting with and modifying workflow graph nodes. ```APIDOC ## GetSimpleAPI ### Description Creates a SimpleAPI interface from nodes within a named group in the workflow to modify parameters. ## GetNodesWithTitle ### Description Retrieves all nodes matching a given title from the workflow graph. ## GetFirstNodeWithTitle ### Description Retrieves the first node matching a given title from the workflow graph. ## GetNodesWithType ### Description Retrieves all nodes of a specific type from the workflow graph. ``` -------------------------------- ### Find First Node by Title in ComfyUI Graph Source: https://context7.com/richinsley/comfy2go/llms.txt Retrieves the first node matching a given title from the workflow graph. Useful for targeting a single, specific node like a CLIP Text Encode node. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("workflow.json") // Find the first CLIP Text Encode node clipNode := graph.GetFirstNodeWithTitle("CLIP Text Encode (Prompt)") if clipNode == nil { log.Fatal("CLIP Text Encode node not found") } // Modify the text property textProp := clipNode.GetPropertyWithName("text") if textProp != nil { textProp.SetValue("a cyberpunk city at night, neon lights, rain") log.Printf("Set prompt text successfully") } } ``` -------------------------------- ### Modify and Save ComfyUI Workflow Source: https://context7.com/richinsley/comfy2go/llms.txt Modifies parameters of a node in the workflow and then serializes the changes back to a JSON file. This is useful for batch processing or parameter sweeps. ```go package main import ( "log" "github.com/richinsley/comfy2go/client" ) func main() { c := client.NewComfyClient("localhost", 8188, nil) c.Init() graph, _, _ := c.NewGraphFromJsonFile("workflow.json") // Modify the graph sampler := graph.GetFirstNodeWithTitle("KSampler") if sampler != nil { sampler.GetPropertyWithName("seed").SetValue(999) sampler.GetPropertyWithName("steps").SetValue(50) } // Convert to JSON string jsonStr, err := graph.GraphToJSON() if err != nil { log.Fatal(err) } log.Printf("JSON length: %d bytes", len(jsonStr)) // Save to file err = graph.SaveGraphToFile("modified_workflow.json") if err != nil { log.Fatal(err) } log.Println("Workflow saved successfully") } ```