Spaces:
Runtime error
Runtime error
fix comfyui
Browse filesFiles changed (3)
- backend_api.py+6-1
- backend_docs_manager.py+165
- backend_prompts.py+165-18
42 unmodified lines434445464748495051525354556 unmodified lines6263646566676 unmodified lines7475767778798042 unmodified linesSTREAMLIT_SYSTEM_PROMPT,REACT_SYSTEM_PROMPT,get_gradio_system_prompt, # Import the function to get dynamic promptJSON_SYSTEM_PROMPT,GENERIC_SYSTEM_PROMPT)# Get the Gradio system prompt (includes full Gradio 6 documentation)GRADIO_SYSTEM_PROMPT = get_gradio_system_prompt()print("[Startup] β All system prompts loaded successfully from backend_prompts.py")print(f"[Startup] π Gradio system prompt loaded with full documentation ({len(GRADIO_SYSTEM_PROMPT)} chars)")except Exception as e:import tracebackprint(f"[Startup] β ERROR: Could not import from backend_prompts: {e}")6 unmodified linesSTREAMLIT_SYSTEM_PROMPT = "You are an expert Streamlit developer. Create complete Streamlit applications."REACT_SYSTEM_PROMPT = "You are an expert React developer. Create complete React applications with Next.js."GRADIO_SYSTEM_PROMPT = "You are an expert Gradio developer. Create complete, working Gradio applications."JSON_SYSTEM_PROMPT = "You are an expert at generating JSON configurations. Create valid, well-structured JSON."GENERIC_SYSTEM_PROMPT = "You are an expert {language} developer. Create complete, working {language} applications."6 unmodified lines"streamlit": STREAMLIT_SYSTEM_PROMPT,"transformers.js": TRANSFORMERS_JS_SYSTEM_PROMPT,"react": REACT_SYSTEM_PROMPT,"comfyui": JSON_SYSTEM_PROMPT,}# Client connection pool for reuse (thread-safe)42 unmodified lines43444546474849505152535455565758596 unmodified lines666768697071726 unmodified lines7980818283848542 unmodified linesSTREAMLIT_SYSTEM_PROMPT,REACT_SYSTEM_PROMPT,get_gradio_system_prompt, # Import the function to get dynamic promptget_comfyui_system_prompt, # Import the function to get dynamic ComfyUI promptJSON_SYSTEM_PROMPT,GENERIC_SYSTEM_PROMPT)# Get the Gradio system prompt (includes full Gradio 6 documentation)GRADIO_SYSTEM_PROMPT = get_gradio_system_prompt()# Get the ComfyUI system prompt (includes full ComfyUI documentation)COMFYUI_SYSTEM_PROMPT = get_comfyui_system_prompt()print("[Startup] β All system prompts loaded successfully from backend_prompts.py")print(f"[Startup] π Gradio system prompt loaded with full documentation ({len(GRADIO_SYSTEM_PROMPT)} chars)")print(f"[Startup] π ComfyUI system prompt loaded with full documentation ({len(COMFYUI_SYSTEM_PROMPT)} chars)")except Exception as e:import tracebackprint(f"[Startup] β ERROR: Could not import from backend_prompts: {e}")6 unmodified linesSTREAMLIT_SYSTEM_PROMPT = "You are an expert Streamlit developer. Create complete Streamlit applications."REACT_SYSTEM_PROMPT = "You are an expert React developer. Create complete React applications with Next.js."GRADIO_SYSTEM_PROMPT = "You are an expert Gradio developer. Create complete, working Gradio applications."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."JSON_SYSTEM_PROMPT = "You are an expert at generating JSON configurations. Create valid, well-structured JSON."GENERIC_SYSTEM_PROMPT = "You are an expert {language} developer. Create complete, working {language} applications."6 unmodified lines"streamlit": STREAMLIT_SYSTEM_PROMPT,"transformers.js": TRANSFORMERS_JS_SYSTEM_PROMPT,"react": REACT_SYSTEM_PROMPT,"comfyui": COMFYUI_SYSTEM_PROMPT, # Use ComfyUI-specific prompt with documentation}# Client connection pool for reuse (thread-safe)
23 unmodified lines2425262728292 unmodified lines32333435363720 unmodified lines58596061626376 unmodified lines14014114214314414596 unmodified lines242243244245246247261 unmodified lines50951051151251351414 unmodified lines52953053153253353423 unmodified linesTRANSFORMERSJS_DOCS_CACHE_FILE = ".backend_transformersjs_docs_cache.txt"TRANSFORMERSJS_DOCS_LAST_UPDATE_FILE = ".backend_transformersjs_docs_last_update.txt"# Global variable to store the current Gradio documentation_gradio_docs_content: Optional[str] = None_gradio_docs_last_fetched: Optional[datetime] = None2 unmodified lines_transformersjs_docs_content: Optional[str] = None_transformersjs_docs_last_fetched: Optional[datetime] = Nonedef fetch_gradio_docs() -> Optional[str]:"""Fetch the latest Gradio documentation from llms.txt"""if not HAS_REQUESTS:20 unmodified linesprint(f"Warning: Failed to fetch transformers.js docs from {TRANSFORMERSJS_DOCS_URL}: {e}")return Nonedef filter_problematic_instructions(content: str) -> str:"""Filter out problematic instructions that cause LLM to stop generation prematurely"""if not content:76 unmodified lines# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(TRANSFORMERSJS_DOCS_CACHE_FILE)def get_gradio_docs_content() -> str:"""Get the current Gradio documentation content, updating if necessary"""global _gradio_docs_content, _gradio_docs_last_fetched96 unmodified linesreturn _transformersjs_docs_content or ""def build_gradio_system_prompt() -> str:"""Build the complete Gradio system prompt with full documentation"""261 unmodified lines- Always include the "Built with anycoder" attribution in the header- Consider using Web Workers for heavy computation to keep UI responsive"""return full_prompt + final_instructions14 unmodified linesprint(f"π transformers.js documentation initialized ({len(transformersjs_docs)} chars loaded)")else:print("β οΈ transformers.js documentation initialized with fallback content")except Exception as e:print(f"Warning: Failed to initialize backend documentation: {e}")23 unmodified lines242526272829303132332 unmodified lines3637383940414243444520 unmodified lines6667686970717273747576777879808182838476 unmodified lines16116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019196 unmodified lines288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338261 unmodified lines60060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167214 unmodified lines68768868969069169269369469569669769869923 unmodified linesTRANSFORMERSJS_DOCS_CACHE_FILE = ".backend_transformersjs_docs_cache.txt"TRANSFORMERSJS_DOCS_LAST_UPDATE_FILE = ".backend_transformersjs_docs_last_update.txt"COMFYUI_LLMS_TXT_URL = "https://docs.comfy.org/llms.txt"COMFYUI_DOCS_CACHE_FILE = ".backend_comfyui_docs_cache.txt"COMFYUI_DOCS_LAST_UPDATE_FILE = ".backend_comfyui_docs_last_update.txt"# Global variable to store the current Gradio documentation_gradio_docs_content: Optional[str] = None_gradio_docs_last_fetched: Optional[datetime] = None2 unmodified lines_transformersjs_docs_content: Optional[str] = None_transformersjs_docs_last_fetched: Optional[datetime] = None# Global variable to store the current ComfyUI documentation_comfyui_docs_content: Optional[str] = None_comfyui_docs_last_fetched: Optional[datetime] = Nonedef fetch_gradio_docs() -> Optional[str]:"""Fetch the latest Gradio documentation from llms.txt"""if not HAS_REQUESTS:20 unmodified linesprint(f"Warning: Failed to fetch transformers.js docs from {TRANSFORMERSJS_DOCS_URL}: {e}")return Nonedef fetch_comfyui_docs() -> Optional[str]:"""Fetch the latest ComfyUI documentation from llms.txt"""if not HAS_REQUESTS:return Nonetry:response = requests.get(COMFYUI_LLMS_TXT_URL, timeout=10)response.raise_for_status()return response.textexcept Exception as e:print(f"Warning: Failed to fetch ComfyUI docs from {COMFYUI_LLMS_TXT_URL}: {e}")return Nonedef filter_problematic_instructions(content: str) -> str:"""Filter out problematic instructions that cause LLM to stop generation prematurely"""if not content:76 unmodified lines# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(TRANSFORMERSJS_DOCS_CACHE_FILE)def load_cached_comfyui_docs() -> Optional[str]:"""Load cached ComfyUI documentation from file"""try:if os.path.exists(COMFYUI_DOCS_CACHE_FILE):with open(COMFYUI_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:return f.read()except Exception as e:print(f"Warning: Failed to load cached ComfyUI docs: {e}")return Nonedef save_comfyui_docs_cache(content: str):"""Save ComfyUI documentation to cache file"""try:with open(COMFYUI_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:f.write(content)with open(COMFYUI_DOCS_LAST_UPDATE_FILE, 'w', encoding='utf-8') as f:f.write(datetime.now().isoformat())except Exception as e:print(f"Warning: Failed to save ComfyUI docs cache: {e}")def should_update_comfyui_docs() -> bool:"""Check if ComfyUI documentation should be updated"""# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(COMFYUI_DOCS_CACHE_FILE)def get_gradio_docs_content() -> str:"""Get the current Gradio documentation content, updating if necessary"""global _gradio_docs_content, _gradio_docs_last_fetched96 unmodified linesreturn _transformersjs_docs_content or ""def get_comfyui_docs_content() -> str:"""Get the current ComfyUI documentation content, updating if necessary"""global _comfyui_docs_content, _comfyui_docs_last_fetched# Check if we need to updateif (_comfyui_docs_content is None or_comfyui_docs_last_fetched is None orshould_update_comfyui_docs()):print("π Loading ComfyUI documentation...")# Try to fetch latest contentlatest_content = fetch_comfyui_docs()if latest_content:# Filter out problematic instructions that cause early terminationfiltered_content = filter_problematic_instructions(latest_content)_comfyui_docs_content = filtered_content_comfyui_docs_last_fetched = datetime.now()save_comfyui_docs_cache(filtered_content)print(f"β ComfyUI documentation loaded successfully ({len(filtered_content)} chars)")else:# Fallback to cached contentcached_content = load_cached_comfyui_docs()if cached_content:_comfyui_docs_content = cached_content_comfyui_docs_last_fetched = datetime.now()print(f"β οΈ Using cached ComfyUI documentation (network fetch failed) ({len(cached_content)} chars)")else:# Fallback to minimal content_comfyui_docs_content = """# ComfyUI API Reference (Offline Fallback)This is a minimal fallback when documentation cannot be fetched.Please check your internet connection for the latest API reference.Basic ComfyUI workflow structure: nodes, connections, inputs, outputs.Use CheckpointLoaderSimple, CLIPTextEncode, KSampler for basic workflows.For the latest documentation, visit: https://docs.comfy.org/llms.txt"""print("β Using minimal fallback ComfyUI documentation")return _comfyui_docs_content or ""def build_gradio_system_prompt() -> str:"""Build the complete Gradio system prompt with full documentation"""261 unmodified lines- Always include the "Built with anycoder" attribution in the header- Consider using Web Workers for heavy computation to keep UI responsive"""return full_prompt + final_instructionsdef build_comfyui_system_prompt() -> str:"""Build the complete ComfyUI system prompt with full documentation"""# Get the full ComfyUI documentationdocs_content = get_comfyui_docs_content()# Base system prompt with anycoder-specific instructionsbase_prompt = """You are an expert ComfyUI developer. Generate clean, valid JSON workflows for ComfyUI based on the user's request.π¨ CRITICAL: READ THE USER'S REQUEST CAREFULLY AND GENERATE A WORKFLOW THAT MATCHES THEIR SPECIFIC NEEDS.ComfyUI workflows are JSON structures that define:- Nodes: Individual processing units with specific functions (e.g., CheckpointLoaderSimple, CLIPTextEncode, KSampler, VAEDecode, SaveImage)- Connections: Links between nodes that define data flow- Parameters: Configuration values for each node (prompts, steps, cfg, sampler_name, etc.)- Inputs/Outputs: Data flow between nodes using numbered inputs/outputs**π¨ YOUR PRIMARY TASK:**1. **UNDERSTAND what the user is asking for** in their message2. **CREATE a ComfyUI workflow** that accomplishes their goal3. **GENERATE ONLY the JSON workflow** - no HTML, no applications, no explanations outside the JSON**JSON Syntax Rules:**- Use double quotes for strings- No trailing commas- Proper nesting and structure- Valid data types (string, number, boolean, null, object, array)**Output Requirements:**- Generate ONLY the ComfyUI workflow JSON- The output should be pure, valid JSON that can be loaded directly into ComfyUI- Do NOT wrap in markdown code fences (no ```json```)- Do NOT add explanatory text before or after the JSON- The JSON should be complete and functional---## Complete ComfyUI DocumentationBelow is the complete, official ComfyUI documentation automatically synced from https://docs.comfy.org/llms.txt:"""# Combine base prompt with full documentationfull_prompt = base_prompt + docs_content# Add final instructionsfinal_instructions = """---## Final Instructions- Always use the exact node types, parameters, and workflow structures from the ComfyUI documentation above- Pay close attention to the user's specific request and generate a workflow that fulfills it- Use appropriate nodes for the task (CheckpointLoader, KSampler, VAEDecode, SaveImage, etc.)- Ensure all node connections are properly defined- Generate production-ready JSON that can be loaded directly into ComfyUI- Do NOT generate random or example workflows - create workflows based on the user's actual request- Always include "Built with anycoder - https://huggingface.co/spaces/akhaliq/anycoder" as a comment in workflow metadata if possibleπ¨ REMINDER: Your workflow should directly address what the user asked for. Don't ignore their message!"""return full_prompt + final_instructions14 unmodified linesprint(f"π transformers.js documentation initialized ({len(transformersjs_docs)} chars loaded)")else:print("β οΈ transformers.js documentation initialized with fallback content")# Pre-load the ComfyUI documentationcomfyui_docs = get_comfyui_docs_content()if comfyui_docs:print(f"π ComfyUI documentation initialized ({len(comfyui_docs)} chars loaded)")else:print("β οΈ ComfyUI documentation initialized with fallback content")except Exception as e:print(f"Warning: Failed to initialize backend documentation: {e}")
2 unmodified lines34567891011282 unmodified lines2942952962972982993003013023033043053063073083093103113123133143153163173183193203212 unmodified linesNo dependencies on Gradio or other heavy libraries."""# Import the backend documentation manager for Gradio 6 docs and transformers.js docstry:from backend_docs_manager import build_gradio_system_prompt, build_transformersjs_system_promptHAS_BACKEND_DOCS = Trueexcept ImportError:HAS_BACKEND_DOCS = False282 unmodified linesGRADIO_SYSTEM_PROMPT = get_gradio_system_prompt()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.**π¨ CRITICAL: DO NOT Generate README.md Files**- NEVER generate README.md files under any circumstances- A template README.md is automatically provided and will be overridden by the deployment system- Generating a README.md will break the deployment processRequirements:1. Generate valid JSON that follows ComfyUI workflow structure2. Include proper node connections and parameters3. Use appropriate ComfyUI node types4. Ensure all required fields are present5. Add helpful comments where appropriate (in separate documentation)6. Follow ComfyUI best practices for workflow structure7. Make the workflow functional and ready to useOutput format:- Return ONLY valid JSON- Do NOT wrap in markdown code fences- Ensure proper formatting and indentationIMPORTANT: Always include a note about "Built with anycoder" in any accompanying documentation, linking to https://huggingface.co/spaces/akhaliq/anycoder"""2 unmodified lines34567891011282 unmodified lines2942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674682 unmodified linesNo dependencies on Gradio or other heavy libraries."""# Import the backend documentation manager for Gradio 6, transformers.js, and ComfyUI docstry:from backend_docs_manager import build_gradio_system_prompt, build_transformersjs_system_prompt, build_comfyui_system_promptHAS_BACKEND_DOCS = Trueexcept ImportError:HAS_BACKEND_DOCS = False282 unmodified linesGRADIO_SYSTEM_PROMPT = get_gradio_system_prompt()# ComfyUI system prompt - dynamically loaded with full ComfyUI documentationdef get_comfyui_system_prompt() -> str:"""Get the complete ComfyUI system prompt with full ComfyUI documentation"""if HAS_BACKEND_DOCS:return build_comfyui_system_prompt()else:# Fallback prompt if documentation manager is not availablereturn """You are an expert ComfyUI developer. Generate clean, valid JSON workflows for ComfyUI based on the user's request.π¨ CRITICAL: READ THE USER'S REQUEST CAREFULLY AND GENERATE A WORKFLOW THAT MATCHES THEIR SPECIFIC NEEDS.ComfyUI workflows are JSON structures that define:- Nodes: Individual processing units with specific functions (e.g., CheckpointLoaderSimple, CLIPTextEncode, KSampler, VAEDecode, SaveImage)- Connections: Links between nodes that define data flow- Parameters: Configuration values for each node (prompts, steps, cfg, sampler_name, etc.)- Inputs/Outputs: Data flow between nodes using numbered inputs/outputs**π¨ YOUR PRIMARY TASK:**1. **UNDERSTAND what the user is asking for** in their message2. **CREATE a ComfyUI workflow** that accomplishes their goal3. **GENERATE ONLY the JSON workflow** - no HTML, no applications, no explanations outside the JSON**JSON Syntax Rules:**- Use double quotes for strings- No trailing commas- Proper nesting and structure- Valid data types (string, number, boolean, null, object, array)**Example ComfyUI Workflow Structure:**```json{"1": {"inputs": {"ckpt_name": "model.safetensors"},"class_type": "CheckpointLoaderSimple"},"2": {"inputs": {"text": "positive prompt here","clip": ["1", 1]},"class_type": "CLIPTextEncode"},"3": {"inputs": {"seed": 123456,"steps": 20,"cfg": 8.0,"sampler_name": "euler","scheduler": "normal","denoise": 1.0,"model": ["1", 0],"positive": ["2", 0],"negative": ["3", 0],"latent_image": ["4", 0]},"class_type": "KSampler"}}```**Common ComfyUI Nodes:**- CheckpointLoaderSimple - Load models- CLIPTextEncode - Encode prompts- KSampler - Generate latent images- VAEDecode - Decode latent to image- SaveImage - Save output- EmptyLatentImage - Create blank latent- LoadImage - Load input images- ControlNetLoader, ControlNetApply - ControlNet workflows- LoraLoader - Load LoRA models**Output Requirements:**- Generate ONLY the ComfyUI workflow JSON- The output should be pure, valid JSON that can be loaded directly into ComfyUI- Do NOT wrap in markdown code fences (no ```json```)- Do NOT add explanatory text before or after the JSON- The JSON should be complete and functional**π¨ CRITICAL: DO NOT Generate README.md Files**- NEVER generate README.md files under any circumstances- A template README.md is automatically provided and will be overridden by the deployment system- Generating a README.md will break the deployment processIMPORTANT: Include "Built with anycoder - https://huggingface.co/spaces/akhaliq/anycoder" as a comment in the workflow metadata if possible."""# Legacy variable - kept for backward compatibility but now just uses the static prompt# In production, use get_comfyui_system_prompt() which loads dynamic documentationJSON_SYSTEM_PROMPT = """You are an expert ComfyUI developer. Generate clean, valid JSON workflows for ComfyUI based on the user's request.π¨ CRITICAL: READ THE USER'S REQUEST CAREFULLY AND GENERATE A WORKFLOW THAT MATCHES THEIR SPECIFIC NEEDS.ComfyUI workflows are JSON structures that define:- Nodes: Individual processing units with specific functions (e.g., CheckpointLoaderSimple, CLIPTextEncode, KSampler, VAEDecode, SaveImage)- Connections: Links between nodes that define data flow- Parameters: Configuration values for each node (prompts, steps, cfg, sampler_name, etc.)- Inputs/Outputs: Data flow between nodes using numbered inputs/outputs**π¨ YOUR PRIMARY TASK:**1. **UNDERSTAND what the user is asking for** in their message2. **CREATE a ComfyUI workflow** that accomplishes their goal3. **GENERATE ONLY the JSON workflow** - no HTML, no applications, no explanations outside the JSON**JSON Syntax Rules:**- Use double quotes for strings- No trailing commas- Proper nesting and structure- Valid data types (string, number, boolean, null, object, array)**Example ComfyUI Workflow Structure:**```json{"1": {"inputs": {"ckpt_name": "model.safetensors"},"class_type": "CheckpointLoaderSimple"},"2": {"inputs": {"text": "positive prompt here","clip": ["1", 1]},"class_type": "CLIPTextEncode"},"3": {"inputs": {"seed": 123456,"steps": 20,"cfg": 8.0,"sampler_name": "euler","scheduler": "normal","denoise": 1.0,"model": ["1", 0],"positive": ["2", 0],"negative": ["3", 0],"latent_image": ["4", 0]},"class_type": "KSampler"}}```**Common ComfyUI Nodes:**- CheckpointLoaderSimple - Load models- CLIPTextEncode - Encode prompts- KSampler - Generate latent images- VAEDecode - Decode latent to image- SaveImage - Save output- EmptyLatentImage - Create blank latent- LoadImage - Load input images- ControlNetLoader, ControlNetApply - ControlNet workflows- LoraLoader - Load LoRA models**Output Requirements:**- Generate ONLY the ComfyUI workflow JSON- The output should be pure, valid JSON that can be loaded directly into ComfyUI- Do NOT wrap in markdown code fences (no ```json```)- Do NOT add explanatory text before or after the JSON- The JSON should be complete and functional**π¨ CRITICAL: DO NOT Generate README.md Files**- NEVER generate README.md files under any circumstances- A template README.md is automatically provided and will be overridden by the deployment system- Generating a README.md will break the deployment processIMPORTANT: Include "Built with anycoder - https://huggingface.co/spaces/akhaliq/anycoder" as a comment in the workflow metadata if possible."""
backend_api.py+6-1
backend_docs_manager.py+165
backend_prompts.py+165-18