Authors’ overview
Workflow generation in visual creation systems such as ComfyUI demands not only syntactic accuracy but also expert-level reasoning over modular compositions. Existing large language model (LLM) approaches often treat this as a direct text-to-JSON generation task, struggling with structural brittleness and lacking the experiential knowledge required for effective design. We argue that successful workflow generation requires modeling knowledge itself, including its structure, hierarchy, and reasoning dynamics. To this end, we propose a knowledge-centric framework that learns to invert, inject, and infer with knowledge across multiple abstraction levels. We first perform knowledge inversion to distill hierarchical representations, ranging from full pseudo-codes and skeletons to high-level strategies, from large collections of real-world workflows. We then conduct knowledge injection through supervised fine-tuning, teaching the model to reason from task descriptions to strategies and from strategies to executable structures. During inference, the model performs reversible reasoning to synthesize executable workflows, augmented by self-refinement for structural coherence. Extensive experiments demonstrate that our method produces workflows with richer node diversity, more coherent structures, and higher execution success rates than existing systems, establishing a new foundation for knowledge-driven, agentic workflow generation.
Introduction
The whirlwind of progress in modern computer vision models has steadily transformed controllable image generation, creation, editing, and processing from laboratory prototypes into powerful tools capable of addressing complex real-world demands. In practice, both technical experts and artists often need to combine and coordinate multiple model components to accomplish those tasks. This results in a non-monolithic, modular composition paradigm for problem solving, where different modules are orchestrated into a Directed Acyclic Graph (DAG), commonly referred to as a workflow, and executed sequentially or conditionally. ComfyUI embodies this philosophy and has become a widely adopted visual programming framework for building such workflows in image creation pipelines. Developing intelligent agents that can automatically generate and refine these workflows is thus not only of great practical relevance but also poses deep scientific challenges.
A ComfyUI workflow can be fully represented as a JSON configuration, which specifies all nodes, parameters, and interconnections. Several recent studies have attempted to leverage large language models (LLMs) to generate these configurations automatically. However, generating valid and effective workflows differs fundamentally from conventional code or text generation. It requires multi-level reasoning that spans from abstract conceptual design to concrete syntactic realization, each demanding distinct forms of knowledge and representation.
At the strategic level, workflow design is an open-ended and experience-driven process rather than a deterministic programming task. ComfyUI provides a rich ecosystem of node types and model variants, each exhibiting complex, often nonlinear behaviors. Their combinations yield an immense compositional space, where small structural changes can produce radically different outcomes. Human designers rely heavily on tacit expertise, iterative experimentation, and intuition to determine whether segmentation is needed, how to arrange processing branches, or which control modules should interact. Such heuristic reasoning, grounded in experiential knowledge, remains highly challenging for LLMs to acquire or reproduce purely from textual data.
At the structural level, even when the high-level strategy is known, translating it into a syntactically correct and executable JSON configuration poses significant challenges. Workflows are large discrete graphs with intricate input–output dependencies. The agent must not only infer the correct topology but also instantiate valid node parameters and maintain type-safe data flow. The brittleness of JSON syntax, coupled with the combinatorial explosion of possible graph structures, makes direct text-to-configuration generation highly unreliable. Small mistakes such as misconnected links or inconsistent parameter bindings can easily make the workflow fail to execute.
ComfyUI and Automatic ComfyUI Assistant
As AI-generated content (AIGC) continues to advance, an increasing number of models and tasks, including text-to-image generation, controllable synthesis, and image editing, are emerging. This shift has moved the community from relying on a single model to composing multiple models to accomplish more complex and customized workflows. Consequently, ComfyUI has become increasingly popular for its flexible, node-based design. ComfyUI connects modular function nodes into directed acyclic workflows, enabling users to build and reuse complex AIGC pipelines. However, these workflows can quickly become complex, often involving nodes for prompt refinement, foreground–background segmentation, super-resolution, and many other operations, which creates a strong demand for automated workflow design tools. To address this need, a variety of automated workflow-design tools have emerged. ComfyUI-Copilot assists users in selecting appropriate parameters and models; ComfyGen focuses specifically on text-to-image generation; ComfyBench and ComfyMind adopt template-based composition strategies that cover most common tasks, with the latter offering tree-structured rollback. Meanwhile, ComfyGPT and ComfyUI-R1 leverage supervised fine-tuning and GRPO reinforcement learning to inject workflow-design knowledge into LLMs. However, when new workflows emerge from the community, these methods must be retrained, limiting their flexibility and scalability for future extensions.
LLMs and LLM-Agent
LLMs have rapidly advanced natural language understanding and generation. BERT introduced bidirectional masked language modeling, greatly improving contextual representation learning. The GPT series shifted toward large-scale autoregressive pretraining, enabling few-shot and in-context learning. Later, ChatGPT and GPT-4 combined instruction tuning and RLHF to enhance alignment and interaction quality. Recent models such as LLaMA, Qwen, Gemini further expand reasoning, efficiency, and multimodal capabilities. Building on these foundations, LLM-powered agents have emerged as autonomous entities capable of perceiving their environments, planning over extended horizons, and interacting with diverse external tools. Compared with traditional symbolic or RL-based agents, those driven by LLMs exhibit superior adaptability, compositional reasoning, and task generalization. Recent research has further enhanced their autonomy through graph-based reasoning, dynamic tool utilization, and self-reflective learning mechanisms. Some studies further explore automated optimization of agentic workflows. For example, GPTSwarm models language agents as nodes in an optimizable graph, while TextGrad introduces gradient-like optimization to iteratively refine prompts and agent behaviors. In addition, recent work investigates scalable evaluation strategies for agent systems, while highlights potential biases in automated evaluation. These LLM-agents are applied widely in the areas of code generation, health care, and scientific discovery. Moreover, as a challenging and complex problem, workflow generation is also well-suited to be addressed by LLM agents, which can decompose tasks, plan multi-step actions, and coordinate across tools.
Overview
Generating a ComfyUI workflow is a complex problem with several layers of reasoning and representation. A workflow is encoded as a JSON graph where nodes are functional modules and edges describe data or control dependencies. Hence, workflow generation is equivalent to producing a valid and executable JSON file, which is far more delicate than ordinary text or code generation.
This complexity arises across several levels. Human experts do not jump from a task instruction directly to JSON. They first form a high level strategy that decides the overall processing plan. Typical decisions include whether segmentation is required, whether branches should process content separately, how many controls to introduce, and how controls interact. This high-level strategy requires substantial domain knowledge and intuitive understanding of visual models and their compositional logic.
Given the strategy, experts construct the workflow topology, that is, a structured connection of modules. This step is also difficult because the graph can be very large, discrete, and complex. Directly generating JSON connections from text is extremely hard for language models due to syntactic brittleness and combinatorial explosion. After the topology is formed, parameter tuning and detailed module configurations can be carried out, which are comparatively more rule-driven or pattern-based. Therefore, workflow generation is a multi-level process, where each level poses distinct reasoning and learning challenges. For example, translating topology into a full workflow can be rule-based, but deriving the topology itself from task instructions and strategies demands substantial knowledge and reasoning ability.
The key idea of our approach is to inverse knowledge, inject knowledge, and infer with knowledge across these hierarchical levels. We systematically learn from large collections of real-world workflows, distill the underlying knowledge representations, and integrate them into a reasoning-capable agent system.
Knowledge Inversion
This hierarchical inversion provides structured knowledge that can later be injected into large language models and utilized by agentic reasoning frameworks for workflow synthesis. Each level can serve as either a hard target or a weak supervision signal for downstream training.
Knowledge Injection
We emphasize that SFT is the primary mechanism for knowledge injection, as it directly teaches the model to produce new reasoning patterns or representations beyond its pretraining scope. By contrast, reinforcement-style alignment methods such as GRPO are mainly effective for local preference optimization within an already feasible generation space. In our setting, where the goal is to endow the model with new capabilities such as planning, decomposition, and workflow construction, SFT serves as the primary knowledge carrier. Some studies indeed demonstrate that in similar settings, SFT continues to play the dominant role for capability injection.
In practice, we fine-tune a large language model, Qwen3-14B, on paired examples of (task, strategy) and (strategy, pseudo-code). During training, we also introduce an auxiliary objective of strategy reasoning extraction, which requires the model to generate intermediate reasoning traces explaining each strategic decision. This auxiliary task regularizes the model to learn the discourse and logical structure of expert reasoning, thereby improving both interpretability and generalization during workflow synthesis.
Knowledge Inference
To further improve robustness, we incorporate self-refinement mechanisms after both the strategy planning and pseudo-code generation stages. The model is prompted to re-evaluate and refine its own outputs, correcting incomplete reasoning steps and enhancing structural coherence. This iterative refinement leads to more complete, logically consistent, and executable workflows.
Discussion with Prior Works
Across the growing body of research on ComfyUI workflow generation, there exists a common aspiration: to reduce the inherent complexity of workflow construction and to inject domain knowledge that enables structured reasoning. Yet the ways the prior works operationalize this goal differ.
Early frameworks such as ComfyAgent and ComfyMind approach the challenge by introducing constrained abstractions. They replaced raw node-level graphs with meta-nodes whose internal connectivity was predefined, lowering combinatorial complexity. This approach, while controllable, inevitably limited expressiveness by constraining the solution space to handcrafted schemas.
Subsequent learning-based systems, including ComfyGPT and ComfyUI-R1, shifted the focus from symbolic simplification to data-driven capability. Instead of fixing structural templates, they trained language or reasoning models on large collections of workflows to predict connections or generate pseudo-codes directly from textual descriptions. However, their knowledge remained implicitly entangled within model parameters, making it difficult to interpret, adapt, or reuse across levels of abstraction.
Our framework departs from both directions. Rather than simplifying the problem or burying knowledge inside opaque model weights, we make knowledge itself the central representational currency. Through knowledge inversion, we decompose complex workflows into hierarchical representations that capture structure, strategy, and reasoning. This paradigm does not merely reduce complexity; it reorganizes it by transforming the implicit experiential knowledge of experts into explicit, learnable, and reusable forms. In doing so, it moves workflow generation from ad-hoc pattern learning toward a principled, knowledge-centric foundation for agentic reasoning.
Workflow Collection
We collected over 10,000 workflow instances from the Internet, covering a wide range of task types and node structures. However, the raw data were highly noisy and redundant. To construct a high-quality, diverse, and semantically consistent dataset, we performed large-scale structural deduplication and filtering. Specifically, we first identified potentially redundant workflows by comparing node-level structural differences. When the ratio of differing nodes between two workflows was below 10%, they were considered structurally similar. In such cases, we employed GPT-4o to evaluate semantic and procedural equivalence, retaining only the version with more standardized and widely used node types. We then merged fully identical workflows by unifying their input entries and removed workflows that were either too simple (fewer than six nodes) or excessively complex (more than ninety nodes). Task descriptions were further normalized and consolidated to eliminate near-duplicate objectives while maintaining structural and semantic diversity.
After multi-stage cleaning and filtering, we obtained a curated dataset of 912 high-quality workflows spanning diverse task distributions and node types. Among them, 882 workflows were used for training, while 30 workflows and their corresponding task queries were reserved for testing. The test workflows were grouped into three categories based on their similarity to the training data: Challenge 1 (high similarity), Challenge 2 (medium similarity), and Real-world Cases (no comparable training samples). Similarity was assessed by a GPT-based evaluator across four dimensions: task objective, technical method, structural form, and application context.
In addition to this split, we further evaluate our method on two external benchmarks to assess generalization ability. First, we evaluate on the FlowBench dataset using a test set of 30 tasks. Second, we conduct evaluation on a subset of ComfyBench consisting of 20 tasks sampled from the Creative and Complex categories. Together, these evaluations cover both in-domain and out-of-domain workflow generation scenarios.
Compared Methods. Given that ComfyBench is the only open-source baseline currently available for this task, we adopt it for comparison and strictly follow its experimental settings. Specifically, we evaluate six representative workflow-generation paradigms established in: Zero-Shot, Few-Shot, Chain-of-Thought (CoT), CoT with Self-Consistency (CoT-SC), Retrieval-Augmented Generation (RAG), and ComfyAgent. These methods correspond to the variants presented in Tables 1, 2, 3, and 4. To ensure fairness, all the methods use GPT-5 as the underlying LLM interface, consistent with the configuration of our refine agent. More details of these baseline methods can be found in the supplementary material.
Evaluation Metrics
NodeComp measures the proportion of valid nodes that are correctly instantiated and involved in at least one connection. A node is considered valid if its type is registered, non-empty, and linked to other nodes. The ratio of valid to total nodes indicates the semantic and functional completeness of the workflow.
LinkComp evaluates the structural correctness of node connections. For each node, input–output consistency is verified: all declared inputs must exist and correctly reference valid outputs, and all output slot indices must remain within bounds. The proportion of nodes passing these checks represents the workflow’s topological soundness.
TaskCons assesses how well the generated workflow fulfills the target task described in the instruction. A GPT-based evaluator scores how well each workflow fulfills its task (e.g., “upscale”, “relighting”, “pose-consistent animation”). Higher scores indicate better alignment between the task intent and the workflow’s functional structure.
In addition, we evaluate executability and task fulfillment through two outcome-level indicators: Pass and Resolve. A workflow is counted as Pass if it executes successfully in ComfyUI without structural or runtime errors, and as Resolve if it additionally produces an output that fulfills the intended task goal. Together, these indicators assess both syntactic validity and the functional effectiveness of workflow generation. To ensure stable and unbiased evaluation, we do not rely on LLM-based judges. Instead, all workflows are executed manually in ComfyUI and the outputs are assessed through human inspection.
Results
Our method also attains markedly higher structural and semantic accuracy than all the other methods. Its NodeComp, LinkComp, and TaskCons scores are consistently far above GPT-5-based methods and ComfyAgent, demonstrating that the generated workflows are both well-formed and aligned with the intended task logic. These results show that template-based or retrieval-driven methods are fundamentally limited, while our model can generate diverse, structurally sound, and task-faithful workflows at scale.
Limitations and Discussion. We observe a limitation when tasks require relatively rare node types. In such cases, the model tends to substitute them with more common nodes, which may break functional dependencies and increase structural errors in the generated workflow. We attribute this behavior mainly to limited coverage of rare nodes in the training data; expanding the diversity and scale of training workflows could help mitigate this issue. In addition, incorporating reinforcement-style optimization (e.g., GRPO) may further improve robustness.
Conclusion
In this work, we present a knowledge-centric framework for workflow generation in visual creation systems such as ComfyUI. Unlike prior LLM-based approaches that treat workflow synthesis as a direct text-to-JSON prediction problem, our method explicitly models the structure, hierarchy, and dynamics of expert knowledge.Through knowledge inversion, the model learns multilevel representations, including pseudo-codes, structural skeletons, and design strategies, from large collections of real workflows. Knowledge injection then guides the model to map tasks to strategies and strategies to executable structures via supervised reasoning. During inference, reversible reasoning and self-refinement enable the generation of coherent, executable workflows. Extensive experiments show that our approach produces more diverse nodes, more consistent compositions, and significantly higher execution success rates than existing methods. Overall, this work establishes a new direction for knowledge-driven, agentic workflow generation in visual creation systems.
Comparative Analysis
The comparative visualization reveals that while both datasets share similar task type distributions, the test dataset exhibits slight variations in the relative proportions of certain task types. Notably, the test dataset shows a higher emphasis on edge control (8 workflows, 26.7%) compared to the training dataset (187 workflows, 21.3%), and similar proportions of style transfer operations (10 workflows, 33.3% in test vs. 312 workflows, 35.5% in training), indicating a focus on more controlled and stylized generation scenarios. The consistent presence of multi-task workflows (averaging 2.7–2.9 task types per item) across both datasets underscores the complexity of real-world image generation pipelines, where users typically require sequential or parallel application of multiple techniques to achieve their desired results.


