akhaliq HF Staff commited on
Commit
35022df
Β·
1 Parent(s): 269deac

fix comfyui

Browse files
Files changed (3) hide show
  1. backend_api.py +6 -1
  2. backend_docs_manager.py +165 -0
  3. backend_prompts.py +165 -18
backend_api.py CHANGED
@@ -43,13 +43,17 @@ try:
43
  STREAMLIT_SYSTEM_PROMPT,
44
  REACT_SYSTEM_PROMPT,
45
  get_gradio_system_prompt, # Import the function to get dynamic prompt
 
46
  JSON_SYSTEM_PROMPT,
47
  GENERIC_SYSTEM_PROMPT
48
  )
49
  # Get the Gradio system prompt (includes full Gradio 6 documentation)
50
  GRADIO_SYSTEM_PROMPT = get_gradio_system_prompt()
 
 
51
  print("[Startup] βœ… All system prompts loaded successfully from backend_prompts.py")
52
  print(f"[Startup] πŸ“š Gradio system prompt loaded with full documentation ({len(GRADIO_SYSTEM_PROMPT)} chars)")
 
53
  except Exception as e:
54
  import traceback
55
  print(f"[Startup] ❌ ERROR: Could not import from backend_prompts: {e}")
@@ -62,6 +66,7 @@ except Exception as e:
62
  STREAMLIT_SYSTEM_PROMPT = "You are an expert Streamlit developer. Create complete Streamlit applications."
63
  REACT_SYSTEM_PROMPT = "You are an expert React developer. Create complete React applications with Next.js."
64
  GRADIO_SYSTEM_PROMPT = "You are an expert Gradio developer. Create complete, working Gradio applications."
 
65
  JSON_SYSTEM_PROMPT = "You are an expert at generating JSON configurations. Create valid, well-structured JSON."
66
  GENERIC_SYSTEM_PROMPT = "You are an expert {language} developer. Create complete, working {language} applications."
67
 
@@ -74,7 +79,7 @@ SYSTEM_PROMPT_CACHE = {
74
  "streamlit": STREAMLIT_SYSTEM_PROMPT,
75
  "transformers.js": TRANSFORMERS_JS_SYSTEM_PROMPT,
76
  "react": REACT_SYSTEM_PROMPT,
77
- "comfyui": JSON_SYSTEM_PROMPT,
78
  }
79
 
80
  # Client connection pool for reuse (thread-safe)
 
43
  STREAMLIT_SYSTEM_PROMPT,
44
  REACT_SYSTEM_PROMPT,
45
  get_gradio_system_prompt, # Import the function to get dynamic prompt
46
+ get_comfyui_system_prompt, # Import the function to get dynamic ComfyUI prompt
47
  JSON_SYSTEM_PROMPT,
48
  GENERIC_SYSTEM_PROMPT
49
  )
50
  # Get the Gradio system prompt (includes full Gradio 6 documentation)
51
  GRADIO_SYSTEM_PROMPT = get_gradio_system_prompt()
52
+ # Get the ComfyUI system prompt (includes full ComfyUI documentation)
53
+ COMFYUI_SYSTEM_PROMPT = get_comfyui_system_prompt()
54
  print("[Startup] βœ… All system prompts loaded successfully from backend_prompts.py")
55
  print(f"[Startup] πŸ“š Gradio system prompt loaded with full documentation ({len(GRADIO_SYSTEM_PROMPT)} chars)")
56
+ print(f"[Startup] πŸ“š ComfyUI system prompt loaded with full documentation ({len(COMFYUI_SYSTEM_PROMPT)} chars)")
57
  except Exception as e:
58
  import traceback
59
  print(f"[Startup] ❌ ERROR: Could not import from backend_prompts: {e}")
 
66
  STREAMLIT_SYSTEM_PROMPT = "You are an expert Streamlit developer. Create complete Streamlit applications."
67
  REACT_SYSTEM_PROMPT = "You are an expert React developer. Create complete React applications with Next.js."
68
  GRADIO_SYSTEM_PROMPT = "You are an expert Gradio developer. Create complete, working Gradio applications."
69
+ COMFYUI_SYSTEM_PROMPT = "You are an expert ComfyUI developer. Generate clean, valid JSON workflows for ComfyUI based on the user's request. READ THE USER'S REQUEST CAREFULLY and create a workflow that matches their specific needs."
70
  JSON_SYSTEM_PROMPT = "You are an expert at generating JSON configurations. Create valid, well-structured JSON."
71
  GENERIC_SYSTEM_PROMPT = "You are an expert {language} developer. Create complete, working {language} applications."
72
 
 
79
  "streamlit": STREAMLIT_SYSTEM_PROMPT,
80
  "transformers.js": TRANSFORMERS_JS_SYSTEM_PROMPT,
81
  "react": REACT_SYSTEM_PROMPT,
82
+ "comfyui": COMFYUI_SYSTEM_PROMPT, # Use ComfyUI-specific prompt with documentation
83
  }
84
 
85
  # Client connection pool for reuse (thread-safe)
backend_docs_manager.py CHANGED
@@ -24,6 +24,10 @@ TRANSFORMERSJS_DOCS_URL = "https://huggingface.co/docs/transformers.js/llms.txt"
24
  TRANSFORMERSJS_DOCS_CACHE_FILE = ".backend_transformersjs_docs_cache.txt"
25
  TRANSFORMERSJS_DOCS_LAST_UPDATE_FILE = ".backend_transformersjs_docs_last_update.txt"
26
 
 
 
 
 
27
  # Global variable to store the current Gradio documentation
28
  _gradio_docs_content: Optional[str] = None
29
  _gradio_docs_last_fetched: Optional[datetime] = None
@@ -32,6 +36,10 @@ _gradio_docs_last_fetched: Optional[datetime] = None
32
  _transformersjs_docs_content: Optional[str] = None
33
  _transformersjs_docs_last_fetched: Optional[datetime] = None
34
 
 
 
 
 
35
  def fetch_gradio_docs() -> Optional[str]:
36
  """Fetch the latest Gradio documentation from llms.txt"""
37
  if not HAS_REQUESTS:
@@ -58,6 +66,19 @@ def fetch_transformersjs_docs() -> Optional[str]:
58
  print(f"Warning: Failed to fetch transformers.js docs from {TRANSFORMERSJS_DOCS_URL}: {e}")
59
  return None
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  def filter_problematic_instructions(content: str) -> str:
62
  """Filter out problematic instructions that cause LLM to stop generation prematurely"""
63
  if not content:
@@ -140,6 +161,31 @@ def should_update_transformersjs_docs() -> bool:
140
  # Only update if we don't have cached content (first run or cache deleted)
141
  return not os.path.exists(TRANSFORMERSJS_DOCS_CACHE_FILE)
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  def get_gradio_docs_content() -> str:
144
  """Get the current Gradio documentation content, updating if necessary"""
145
  global _gradio_docs_content, _gradio_docs_last_fetched
@@ -242,6 +288,51 @@ For the latest documentation, visit: https://huggingface.co/docs/transformers.js
242
 
243
  return _transformersjs_docs_content or ""
244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  def build_gradio_system_prompt() -> str:
246
  """Build the complete Gradio system prompt with full documentation"""
247
 
@@ -509,6 +600,73 @@ Below is the complete, official transformers.js documentation automatically sync
509
  - Always include the "Built with anycoder" attribution in the header
510
  - Consider using Web Workers for heavy computation to keep UI responsive
511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  """
513
 
514
  return full_prompt + final_instructions
@@ -529,6 +687,13 @@ def initialize_backend_docs():
529
  print(f"πŸš€ transformers.js documentation initialized ({len(transformersjs_docs)} chars loaded)")
530
  else:
531
  print("⚠️ transformers.js documentation initialized with fallback content")
 
 
 
 
 
 
 
532
 
533
  except Exception as e:
534
  print(f"Warning: Failed to initialize backend documentation: {e}")
 
24
  TRANSFORMERSJS_DOCS_CACHE_FILE = ".backend_transformersjs_docs_cache.txt"
25
  TRANSFORMERSJS_DOCS_LAST_UPDATE_FILE = ".backend_transformersjs_docs_last_update.txt"
26
 
27
+ COMFYUI_LLMS_TXT_URL = "https://docs.comfy.org/llms.txt"
28
+ COMFYUI_DOCS_CACHE_FILE = ".backend_comfyui_docs_cache.txt"
29
+ COMFYUI_DOCS_LAST_UPDATE_FILE = ".backend_comfyui_docs_last_update.txt"
30
+
31
  # Global variable to store the current Gradio documentation
32
  _gradio_docs_content: Optional[str] = None
33
  _gradio_docs_last_fetched: Optional[datetime] = None
 
36
  _transformersjs_docs_content: Optional[str] = None
37
  _transformersjs_docs_last_fetched: Optional[datetime] = None
38
 
39
+ # Global variable to store the current ComfyUI documentation
40
+ _comfyui_docs_content: Optional[str] = None
41
+ _comfyui_docs_last_fetched: Optional[datetime] = None
42
+
43
  def fetch_gradio_docs() -> Optional[str]:
44
  """Fetch the latest Gradio documentation from llms.txt"""
45
  if not HAS_REQUESTS:
 
66
  print(f"Warning: Failed to fetch transformers.js docs from {TRANSFORMERSJS_DOCS_URL}: {e}")
67
  return None
68
 
69
+ def fetch_comfyui_docs() -> Optional[str]:
70
+ """Fetch the latest ComfyUI documentation from llms.txt"""
71
+ if not HAS_REQUESTS:
72
+ return None
73
+
74
+ try:
75
+ response = requests.get(COMFYUI_LLMS_TXT_URL, timeout=10)
76
+ response.raise_for_status()
77
+ return response.text
78
+ except Exception as e:
79
+ print(f"Warning: Failed to fetch ComfyUI docs from {COMFYUI_LLMS_TXT_URL}: {e}")
80
+ return None
81
+
82
  def filter_problematic_instructions(content: str) -> str:
83
  """Filter out problematic instructions that cause LLM to stop generation prematurely"""
84
  if not content:
 
161
  # Only update if we don't have cached content (first run or cache deleted)
162
  return not os.path.exists(TRANSFORMERSJS_DOCS_CACHE_FILE)
163
 
164
+ def load_cached_comfyui_docs() -> Optional[str]:
165
+ """Load cached ComfyUI documentation from file"""
166
+ try:
167
+ if os.path.exists(COMFYUI_DOCS_CACHE_FILE):
168
+ with open(COMFYUI_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:
169
+ return f.read()
170
+ except Exception as e:
171
+ print(f"Warning: Failed to load cached ComfyUI docs: {e}")
172
+ return None
173
+
174
+ def save_comfyui_docs_cache(content: str):
175
+ """Save ComfyUI documentation to cache file"""
176
+ try:
177
+ with open(COMFYUI_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:
178
+ f.write(content)
179
+ with open(COMFYUI_DOCS_LAST_UPDATE_FILE, 'w', encoding='utf-8') as f:
180
+ f.write(datetime.now().isoformat())
181
+ except Exception as e:
182
+ print(f"Warning: Failed to save ComfyUI docs cache: {e}")
183
+
184
+ def should_update_comfyui_docs() -> bool:
185
+ """Check if ComfyUI documentation should be updated"""
186
+ # Only update if we don't have cached content (first run or cache deleted)
187
+ return not os.path.exists(COMFYUI_DOCS_CACHE_FILE)
188
+
189
  def get_gradio_docs_content() -> str:
190
  """Get the current Gradio documentation content, updating if necessary"""
191
  global _gradio_docs_content, _gradio_docs_last_fetched
 
288
 
289
  return _transformersjs_docs_content or ""
290
 
291
+ def get_comfyui_docs_content() -> str:
292
+ """Get the current ComfyUI documentation content, updating if necessary"""
293
+ global _comfyui_docs_content, _comfyui_docs_last_fetched
294
+
295
+ # Check if we need to update
296
+ if (_comfyui_docs_content is None or
297
+ _comfyui_docs_last_fetched is None or
298
+ should_update_comfyui_docs()):
299
+
300
+ print("πŸ“š Loading ComfyUI documentation...")
301
+
302
+ # Try to fetch latest content
303
+ latest_content = fetch_comfyui_docs()
304
+
305
+ if latest_content:
306
+ # Filter out problematic instructions that cause early termination
307
+ filtered_content = filter_problematic_instructions(latest_content)
308
+ _comfyui_docs_content = filtered_content
309
+ _comfyui_docs_last_fetched = datetime.now()
310
+ save_comfyui_docs_cache(filtered_content)
311
+ print(f"βœ… ComfyUI documentation loaded successfully ({len(filtered_content)} chars)")
312
+ else:
313
+ # Fallback to cached content
314
+ cached_content = load_cached_comfyui_docs()
315
+ if cached_content:
316
+ _comfyui_docs_content = cached_content
317
+ _comfyui_docs_last_fetched = datetime.now()
318
+ print(f"⚠️ Using cached ComfyUI documentation (network fetch failed) ({len(cached_content)} chars)")
319
+ else:
320
+ # Fallback to minimal content
321
+ _comfyui_docs_content = """
322
+ # ComfyUI API Reference (Offline Fallback)
323
+
324
+ This is a minimal fallback when documentation cannot be fetched.
325
+ Please check your internet connection for the latest API reference.
326
+
327
+ Basic ComfyUI workflow structure: nodes, connections, inputs, outputs.
328
+ Use CheckpointLoaderSimple, CLIPTextEncode, KSampler for basic workflows.
329
+
330
+ For the latest documentation, visit: https://docs.comfy.org/llms.txt
331
+ """
332
+ print("❌ Using minimal fallback ComfyUI documentation")
333
+
334
+ return _comfyui_docs_content or ""
335
+
336
  def build_gradio_system_prompt() -> str:
337
  """Build the complete Gradio system prompt with full documentation"""
338
 
 
600
  - Always include the "Built with anycoder" attribution in the header
601
  - Consider using Web Workers for heavy computation to keep UI responsive
602
 
603
+ """
604
+
605
+ return full_prompt + final_instructions
606
+
607
+ def build_comfyui_system_prompt() -> str:
608
+ """Build the complete ComfyUI system prompt with full documentation"""
609
+
610
+ # Get the full ComfyUI documentation
611
+ docs_content = get_comfyui_docs_content()
612
+
613
+ # Base system prompt with anycoder-specific instructions
614
+ base_prompt = """You are an expert ComfyUI developer. Generate clean, valid JSON workflows for ComfyUI based on the user's request.
615
+
616
+ 🚨 CRITICAL: READ THE USER'S REQUEST CAREFULLY AND GENERATE A WORKFLOW THAT MATCHES THEIR SPECIFIC NEEDS.
617
+
618
+ ComfyUI workflows are JSON structures that define:
619
+ - Nodes: Individual processing units with specific functions (e.g., CheckpointLoaderSimple, CLIPTextEncode, KSampler, VAEDecode, SaveImage)
620
+ - Connections: Links between nodes that define data flow
621
+ - Parameters: Configuration values for each node (prompts, steps, cfg, sampler_name, etc.)
622
+ - Inputs/Outputs: Data flow between nodes using numbered inputs/outputs
623
+
624
+ **🚨 YOUR PRIMARY TASK:**
625
+ 1. **UNDERSTAND what the user is asking for** in their message
626
+ 2. **CREATE a ComfyUI workflow** that accomplishes their goal
627
+ 3. **GENERATE ONLY the JSON workflow** - no HTML, no applications, no explanations outside the JSON
628
+
629
+ **JSON Syntax Rules:**
630
+ - Use double quotes for strings
631
+ - No trailing commas
632
+ - Proper nesting and structure
633
+ - Valid data types (string, number, boolean, null, object, array)
634
+
635
+ **Output Requirements:**
636
+ - Generate ONLY the ComfyUI workflow JSON
637
+ - The output should be pure, valid JSON that can be loaded directly into ComfyUI
638
+ - Do NOT wrap in markdown code fences (no ```json```)
639
+ - Do NOT add explanatory text before or after the JSON
640
+ - The JSON should be complete and functional
641
+
642
+ ---
643
+
644
+ ## Complete ComfyUI Documentation
645
+
646
+ Below is the complete, official ComfyUI documentation automatically synced from https://docs.comfy.org/llms.txt:
647
+
648
+ """
649
+
650
+ # Combine base prompt with full documentation
651
+ full_prompt = base_prompt + docs_content
652
+
653
+ # Add final instructions
654
+ final_instructions = """
655
+
656
+ ---
657
+
658
+ ## Final Instructions
659
+
660
+ - Always use the exact node types, parameters, and workflow structures from the ComfyUI documentation above
661
+ - Pay close attention to the user's specific request and generate a workflow that fulfills it
662
+ - Use appropriate nodes for the task (CheckpointLoader, KSampler, VAEDecode, SaveImage, etc.)
663
+ - Ensure all node connections are properly defined
664
+ - Generate production-ready JSON that can be loaded directly into ComfyUI
665
+ - Do NOT generate random or example workflows - create workflows based on the user's actual request
666
+ - Always include "Built with anycoder - https://huggingface.co/spaces/akhaliq/anycoder" as a comment in workflow metadata if possible
667
+
668
+ 🚨 REMINDER: Your workflow should directly address what the user asked for. Don't ignore their message!
669
+
670
  """
671
 
672
  return full_prompt + final_instructions
 
687
  print(f"πŸš€ transformers.js documentation initialized ({len(transformersjs_docs)} chars loaded)")
688
  else:
689
  print("⚠️ transformers.js documentation initialized with fallback content")
690
+
691
+ # Pre-load the ComfyUI documentation
692
+ comfyui_docs = get_comfyui_docs_content()
693
+ if comfyui_docs:
694
+ print(f"πŸš€ ComfyUI documentation initialized ({len(comfyui_docs)} chars loaded)")
695
+ else:
696
+ print("⚠️ ComfyUI documentation initialized with fallback content")
697
 
698
  except Exception as e:
699
  print(f"Warning: Failed to initialize backend documentation: {e}")
backend_prompts.py CHANGED
@@ -3,9 +3,9 @@ Standalone system prompts for AnyCoder backend.
3
  No dependencies on Gradio or other heavy libraries.
4
  """
5
 
6
- # Import the backend documentation manager for Gradio 6 docs and transformers.js docs
7
  try:
8
- from backend_docs_manager import build_gradio_system_prompt, build_transformersjs_system_prompt
9
  HAS_BACKEND_DOCS = True
10
  except ImportError:
11
  HAS_BACKEND_DOCS = False
@@ -294,28 +294,175 @@ IMPORTANT: Always include "Built with anycoder" as clickable text in the header/
294
  GRADIO_SYSTEM_PROMPT = get_gradio_system_prompt()
295
 
296
 
297
- JSON_SYSTEM_PROMPT = """You are an expert at generating JSON configurations for ComfyUI workflows. Create valid, well-structured JSON that can be loaded into ComfyUI.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
 
299
  **🚨 CRITICAL: DO NOT Generate README.md Files**
300
  - NEVER generate README.md files under any circumstances
301
  - A template README.md is automatically provided and will be overridden by the deployment system
302
  - Generating a README.md will break the deployment process
303
 
304
- Requirements:
305
- 1. Generate valid JSON that follows ComfyUI workflow structure
306
- 2. Include proper node connections and parameters
307
- 3. Use appropriate ComfyUI node types
308
- 4. Ensure all required fields are present
309
- 5. Add helpful comments where appropriate (in separate documentation)
310
- 6. Follow ComfyUI best practices for workflow structure
311
- 7. Make the workflow functional and ready to use
312
-
313
- Output format:
314
- - Return ONLY valid JSON
315
- - Do NOT wrap in markdown code fences
316
- - Ensure proper formatting and indentation
317
-
318
- IMPORTANT: Always include a note about "Built with anycoder" in any accompanying documentation, linking to https://huggingface.co/spaces/akhaliq/anycoder
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
  """
320
 
321
 
 
3
  No dependencies on Gradio or other heavy libraries.
4
  """
5
 
6
+ # Import the backend documentation manager for Gradio 6, transformers.js, and ComfyUI docs
7
  try:
8
+ from backend_docs_manager import build_gradio_system_prompt, build_transformersjs_system_prompt, build_comfyui_system_prompt
9
  HAS_BACKEND_DOCS = True
10
  except ImportError:
11
  HAS_BACKEND_DOCS = False
 
294
  GRADIO_SYSTEM_PROMPT = get_gradio_system_prompt()
295
 
296
 
297
+ # ComfyUI system prompt - dynamically loaded with full ComfyUI documentation
298
+ def get_comfyui_system_prompt() -> str:
299
+ """Get the complete ComfyUI system prompt with full ComfyUI documentation"""
300
+ if HAS_BACKEND_DOCS:
301
+ return build_comfyui_system_prompt()
302
+ else:
303
+ # Fallback prompt if documentation manager is not available
304
+ return """You are an expert ComfyUI developer. Generate clean, valid JSON workflows for ComfyUI based on the user's request.
305
+
306
+ 🚨 CRITICAL: READ THE USER'S REQUEST CAREFULLY AND GENERATE A WORKFLOW THAT MATCHES THEIR SPECIFIC NEEDS.
307
+
308
+ ComfyUI workflows are JSON structures that define:
309
+ - Nodes: Individual processing units with specific functions (e.g., CheckpointLoaderSimple, CLIPTextEncode, KSampler, VAEDecode, SaveImage)
310
+ - Connections: Links between nodes that define data flow
311
+ - Parameters: Configuration values for each node (prompts, steps, cfg, sampler_name, etc.)
312
+ - Inputs/Outputs: Data flow between nodes using numbered inputs/outputs
313
+
314
+ **🚨 YOUR PRIMARY TASK:**
315
+ 1. **UNDERSTAND what the user is asking for** in their message
316
+ 2. **CREATE a ComfyUI workflow** that accomplishes their goal
317
+ 3. **GENERATE ONLY the JSON workflow** - no HTML, no applications, no explanations outside the JSON
318
+
319
+ **JSON Syntax Rules:**
320
+ - Use double quotes for strings
321
+ - No trailing commas
322
+ - Proper nesting and structure
323
+ - Valid data types (string, number, boolean, null, object, array)
324
+
325
+ **Example ComfyUI Workflow Structure:**
326
+ ```json
327
+ {
328
+ "1": {
329
+ "inputs": {
330
+ "ckpt_name": "model.safetensors"
331
+ },
332
+ "class_type": "CheckpointLoaderSimple"
333
+ },
334
+ "2": {
335
+ "inputs": {
336
+ "text": "positive prompt here",
337
+ "clip": ["1", 1]
338
+ },
339
+ "class_type": "CLIPTextEncode"
340
+ },
341
+ "3": {
342
+ "inputs": {
343
+ "seed": 123456,
344
+ "steps": 20,
345
+ "cfg": 8.0,
346
+ "sampler_name": "euler",
347
+ "scheduler": "normal",
348
+ "denoise": 1.0,
349
+ "model": ["1", 0],
350
+ "positive": ["2", 0],
351
+ "negative": ["3", 0],
352
+ "latent_image": ["4", 0]
353
+ },
354
+ "class_type": "KSampler"
355
+ }
356
+ }
357
+ ```
358
+
359
+ **Common ComfyUI Nodes:**
360
+ - CheckpointLoaderSimple - Load models
361
+ - CLIPTextEncode - Encode prompts
362
+ - KSampler - Generate latent images
363
+ - VAEDecode - Decode latent to image
364
+ - SaveImage - Save output
365
+ - EmptyLatentImage - Create blank latent
366
+ - LoadImage - Load input images
367
+ - ControlNetLoader, ControlNetApply - ControlNet workflows
368
+ - LoraLoader - Load LoRA models
369
+
370
+ **Output Requirements:**
371
+ - Generate ONLY the ComfyUI workflow JSON
372
+ - The output should be pure, valid JSON that can be loaded directly into ComfyUI
373
+ - Do NOT wrap in markdown code fences (no ```json```)
374
+ - Do NOT add explanatory text before or after the JSON
375
+ - The JSON should be complete and functional
376
 
377
  **🚨 CRITICAL: DO NOT Generate README.md Files**
378
  - NEVER generate README.md files under any circumstances
379
  - A template README.md is automatically provided and will be overridden by the deployment system
380
  - Generating a README.md will break the deployment process
381
 
382
+ IMPORTANT: Include "Built with anycoder - https://huggingface.co/spaces/akhaliq/anycoder" as a comment in the workflow metadata if possible.
383
+ """
384
+
385
+ # Legacy variable - kept for backward compatibility but now just uses the static prompt
386
+ # In production, use get_comfyui_system_prompt() which loads dynamic documentation
387
+ JSON_SYSTEM_PROMPT = """You are an expert ComfyUI developer. Generate clean, valid JSON workflows for ComfyUI based on the user's request.
388
+
389
+ 🚨 CRITICAL: READ THE USER'S REQUEST CAREFULLY AND GENERATE A WORKFLOW THAT MATCHES THEIR SPECIFIC NEEDS.
390
+
391
+ ComfyUI workflows are JSON structures that define:
392
+ - Nodes: Individual processing units with specific functions (e.g., CheckpointLoaderSimple, CLIPTextEncode, KSampler, VAEDecode, SaveImage)
393
+ - Connections: Links between nodes that define data flow
394
+ - Parameters: Configuration values for each node (prompts, steps, cfg, sampler_name, etc.)
395
+ - Inputs/Outputs: Data flow between nodes using numbered inputs/outputs
396
+
397
+ **🚨 YOUR PRIMARY TASK:**
398
+ 1. **UNDERSTAND what the user is asking for** in their message
399
+ 2. **CREATE a ComfyUI workflow** that accomplishes their goal
400
+ 3. **GENERATE ONLY the JSON workflow** - no HTML, no applications, no explanations outside the JSON
401
+
402
+ **JSON Syntax Rules:**
403
+ - Use double quotes for strings
404
+ - No trailing commas
405
+ - Proper nesting and structure
406
+ - Valid data types (string, number, boolean, null, object, array)
407
+
408
+ **Example ComfyUI Workflow Structure:**
409
+ ```json
410
+ {
411
+ "1": {
412
+ "inputs": {
413
+ "ckpt_name": "model.safetensors"
414
+ },
415
+ "class_type": "CheckpointLoaderSimple"
416
+ },
417
+ "2": {
418
+ "inputs": {
419
+ "text": "positive prompt here",
420
+ "clip": ["1", 1]
421
+ },
422
+ "class_type": "CLIPTextEncode"
423
+ },
424
+ "3": {
425
+ "inputs": {
426
+ "seed": 123456,
427
+ "steps": 20,
428
+ "cfg": 8.0,
429
+ "sampler_name": "euler",
430
+ "scheduler": "normal",
431
+ "denoise": 1.0,
432
+ "model": ["1", 0],
433
+ "positive": ["2", 0],
434
+ "negative": ["3", 0],
435
+ "latent_image": ["4", 0]
436
+ },
437
+ "class_type": "KSampler"
438
+ }
439
+ }
440
+ ```
441
+
442
+ **Common ComfyUI Nodes:**
443
+ - CheckpointLoaderSimple - Load models
444
+ - CLIPTextEncode - Encode prompts
445
+ - KSampler - Generate latent images
446
+ - VAEDecode - Decode latent to image
447
+ - SaveImage - Save output
448
+ - EmptyLatentImage - Create blank latent
449
+ - LoadImage - Load input images
450
+ - ControlNetLoader, ControlNetApply - ControlNet workflows
451
+ - LoraLoader - Load LoRA models
452
+
453
+ **Output Requirements:**
454
+ - Generate ONLY the ComfyUI workflow JSON
455
+ - The output should be pure, valid JSON that can be loaded directly into ComfyUI
456
+ - Do NOT wrap in markdown code fences (no ```json```)
457
+ - Do NOT add explanatory text before or after the JSON
458
+ - The JSON should be complete and functional
459
+
460
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
461
+ - NEVER generate README.md files under any circumstances
462
+ - A template README.md is automatically provided and will be overridden by the deployment system
463
+ - Generating a README.md will break the deployment process
464
+
465
+ IMPORTANT: Include "Built with anycoder - https://huggingface.co/spaces/akhaliq/anycoder" as a comment in the workflow metadata if possible.
466
  """
467
 
468