update system prompt comfy
Browse files68 unmodified lines6970717273744 unmodified lines79808182838446 unmodified lines1311321331341351369 unmodified lines14614714814915015119 unmodified lines17117217317417517637 unmodified lines214215216217218219546 unmodified lines7667677687697707716 unmodified lines778779780781782783442 unmodified lines122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712488680 unmodified lines99299930993199329933993468 unmodified lines_gradio_docs_content: str | None = None_gradio_docs_last_fetched: Optional[datetime] = Nonedef fetch_gradio_docs() -> str | None:"""Fetch the latest Gradio documentation from llms.txt"""try:4 unmodified linesprint(f"Warning: Failed to fetch Gradio docs from {GRADIO_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:46 unmodified linesexcept Exception as e:print(f"Warning: Failed to save Gradio docs cache: {e}")def get_last_update_time() -> Optional[datetime]:"""Get the last update time from file"""try:9 unmodified lines# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(GRADIO_DOCS_CACHE_FILE)def force_update_gradio_docs():"""Force an update of Gradio documentation (useful when app is updated).19 unmodified linesprint("β Failed to update Gradio documentation")return Falsedef get_gradio_docs_content() -> str:"""Get the current Gradio documentation content, updating if necessary"""global _gradio_docs_content, _gradio_docs_last_fetched37 unmodified linesreturn _gradio_docs_content or ""def update_gradio_system_prompts():"""Update the global Gradio system prompts with latest documentation"""global GRADIO_SYSTEM_PROMPT, GRADIO_SYSTEM_PROMPT_WITH_SEARCH546 unmodified linesGRADIO_SYSTEM_PROMPT = base_prompt + docs_content + "\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.\n\nIMPORTANT: Always include \"Built with anycoder\" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"GRADIO_SYSTEM_PROMPT_WITH_SEARCH = search_prompt + docs_content + "\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.\n\nIMPORTANT: Always include \"Built with anycoder\" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"# Initialize Gradio documentation on startupdef initialize_gradio_docs():"""Initialize Gradio documentation on application startup"""6 unmodified linesexcept Exception as e:print(f"Warning: Failed to initialize Gradio documentation: {e}")# ConfigurationHTML_SYSTEM_PROMPT = """ONLY USE HTML, CSS AND JAVASCRIPT. If you want to use ICON make sure to import the library first. Try to create the best UI possible by using only HTML, CSS and JAVASCRIPT. MAKE IT RESPONSIVE USING MODERN CSS. Use as much as you can modern CSS for the styling, if you can't do something with modern CSS, then use custom CSS. Also, try to elaborate as much as you can, to create something unique. ALWAYS GIVE THE RESPONSE INTO A SINGLE HTML FILE442 unmodified lines# All Gradio API documentation is now dynamically loaded from https://www.gradio.app/llms.txtJSON_SYSTEM_PROMPT = """You are an expert JSON developer. Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:- Use double quotes for strings- No trailing commas- Proper nesting and structure- Valid data types (string, number, boolean, null, object, array)Generate ONLY the JSON data requested - no HTML, no applications, no explanations outside the JSON. The output should be pure, valid JSON that can be parsed directly."""JSON_SYSTEM_PROMPT_WITH_SEARCH = """You are an expert JSON developer. You have access to real-time web search. When needed, use web search to find the latest information or data structures for your JSON generation.Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:- Use double quotes for strings- No trailing commas- Proper nesting and structure- Valid data types (string, number, boolean, null, object, array)Generate ONLY the JSON data requested - no HTML, no applications, no explanations outside the JSON. The output should be pure, valid JSON that can be parsed directly."""GENERIC_SYSTEM_PROMPT = """You are an expert {language} developer. Write clean, idiomatic, and runnable {language} code for the user's request. If possible, include comments and best practices. Generate complete, working code that can be run immediately. If the user provides a file or other context, use it as a reference. If the code is for a script or app, make it as self-contained as possible.8680 unmodified lines# Initialize Gradio documentation systeminitialize_gradio_docs()# Clean up any orphaned temporary files from previous runscleanup_all_temp_media_on_startup()68 unmodified lines697071727374757677787980818283844 unmodified lines899091929394959697989910010110210310446 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731741751769 unmodified lines18618718818919019119219319419519619 unmodified lines21621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524637 unmodified lines284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332546 unmodified lines8798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329336 unmodified lines940941942943944945946947948949950951952953954955956957442 unmodified lines140014011402140314041405140614071408140914108680 unmodified lines10091100921009310094100951009610097100981009968 unmodified lines_gradio_docs_content: str | None = None_gradio_docs_last_fetched: Optional[datetime] = None# ComfyUI Documentation Auto-Update SystemCOMFYUI_LLMS_TXT_URL = "https://docs.comfy.org/llms.txt"COMFYUI_DOCS_CACHE_FILE = ".comfyui_docs_cache.txt"COMFYUI_DOCS_LAST_UPDATE_FILE = ".comfyui_docs_last_update.txt"COMFYUI_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer# Global variable to store the current ComfyUI documentation_comfyui_docs_content: str | None = None_comfyui_docs_last_fetched: Optional[datetime] = Nonedef fetch_gradio_docs() -> str | None:"""Fetch the latest Gradio documentation from llms.txt"""try:4 unmodified linesprint(f"Warning: Failed to fetch Gradio docs from {GRADIO_LLMS_TXT_URL}: {e}")return Nonedef fetch_comfyui_docs() -> str | None:"""Fetch the latest ComfyUI documentation from llms.txt"""try: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:46 unmodified linesexcept Exception as e:print(f"Warning: Failed to save Gradio docs cache: {e}")def load_comfyui_docs_cache() -> str | None:"""Load ComfyUI documentation from cache 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 get_last_update_time() -> Optional[datetime]:"""Get the last update time from file"""try:9 unmodified lines# Only update if we don't have cached content (first run or cache deleted)return not os.path.exists(GRADIO_DOCS_CACHE_FILE)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 force_update_gradio_docs():"""Force an update of Gradio documentation (useful when app is updated).19 unmodified linesprint("β Failed to update Gradio documentation")return Falsedef force_update_comfyui_docs():"""Force an update of ComfyUI documentation (useful when app is updated).To manually refresh docs, you can call this function or simply delete the cache file:rm .comfyui_docs_cache.txt && restart the app"""global _comfyui_docs_content, _comfyui_docs_last_fetchedprint("π Forcing ComfyUI documentation update...")latest_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)update_json_system_prompts()print("β ComfyUI documentation updated successfully")return Trueelse:print("β Failed to update ComfyUI documentation")return Falsedef get_gradio_docs_content() -> str:"""Get the current Gradio documentation content, updating if necessary"""global _gradio_docs_content, _gradio_docs_last_fetched37 unmodified linesreturn _gradio_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("Updating 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("β ComfyUI documentation updated successfully")else:# Fallback to cached contentcached_content = load_comfyui_docs_cache()if cached_content:_comfyui_docs_content = cached_content_comfyui_docs_last_fetched = datetime.now()print("β οΈ Using cached ComfyUI documentation (network fetch failed)")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."""print("β Using minimal fallback documentation")return _comfyui_docs_content or ""def update_gradio_system_prompts():"""Update the global Gradio system prompts with latest documentation"""global GRADIO_SYSTEM_PROMPT, GRADIO_SYSTEM_PROMPT_WITH_SEARCH546 unmodified linesGRADIO_SYSTEM_PROMPT = base_prompt + docs_content + "\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.\n\nIMPORTANT: Always include \"Built with anycoder\" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"GRADIO_SYSTEM_PROMPT_WITH_SEARCH = search_prompt + docs_content + "\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.\n\nIMPORTANT: Always include \"Built with anycoder\" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"def update_json_system_prompts():"""Update the global JSON system prompts with latest ComfyUI documentation"""global JSON_SYSTEM_PROMPT, JSON_SYSTEM_PROMPT_WITH_SEARCHdocs_content = get_comfyui_docs_content()# Base system promptbase_prompt = """You are an expert JSON developer. Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:- Use double quotes for strings- No trailing commas- Proper nesting and structure- Valid data types (string, number, boolean, null, object, array)Generate ONLY the JSON data requested - no HTML, no applications, no explanations outside the JSON. The output should be pure, valid JSON that can be parsed directly."""# Search-enabled system promptsearch_prompt = """You are an expert JSON developer. You have access to real-time web search. When needed, use web search to find the latest information or data structures for your JSON generation.Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:- Use double quotes for strings- No trailing commas- Proper nesting and structure- Valid data types (string, number, boolean, null, object, array)Generate ONLY the JSON data requested - no HTML, no applications, no explanations outside the JSON. The output should be pure, valid JSON that can be parsed directly."""# Add ComfyUI documentation if availableif docs_content.strip():comfyui_section = f"""## ComfyUI Reference DocumentationWhen generating JSON data related to ComfyUI workflows, nodes, or configurations, use this reference:{docs_content}This reference is automatically synced from https://docs.comfy.org/llms.txt to ensure accuracy."""base_prompt += comfyui_sectionsearch_prompt += comfyui_section# Update the promptsJSON_SYSTEM_PROMPT = base_promptJSON_SYSTEM_PROMPT_WITH_SEARCH = search_prompt# Initialize Gradio documentation on startupdef initialize_gradio_docs():"""Initialize Gradio documentation on application startup"""6 unmodified linesexcept Exception as e:print(f"Warning: Failed to initialize Gradio documentation: {e}")# Initialize ComfyUI documentation on startupdef initialize_comfyui_docs():"""Initialize ComfyUI documentation on application startup"""try:update_json_system_prompts()if should_update_comfyui_docs():print("π ComfyUI documentation system initialized (fetched fresh content)")else:print("π ComfyUI documentation system initialized (using cached content)")except Exception as e:print(f"Warning: Failed to initialize ComfyUI documentation: {e}")# ConfigurationHTML_SYSTEM_PROMPT = """ONLY USE HTML, CSS AND JAVASCRIPT. If you want to use ICON make sure to import the library first. Try to create the best UI possible by using only HTML, CSS and JAVASCRIPT. MAKE IT RESPONSIVE USING MODERN CSS. Use as much as you can modern CSS for the styling, if you can't do something with modern CSS, then use custom CSS. Also, try to elaborate as much as you can, to create something unique. ALWAYS GIVE THE RESPONSE INTO A SINGLE HTML FILE442 unmodified lines# All Gradio API documentation is now dynamically loaded from https://www.gradio.app/llms.txt# JSON system prompts will be dynamically populated by update_json_system_prompts()JSON_SYSTEM_PROMPT = ""JSON_SYSTEM_PROMPT_WITH_SEARCH = ""# All ComfyUI API documentation is now dynamically loaded from https://docs.comfy.org/llms.txtGENERIC_SYSTEM_PROMPT = """You are an expert {language} developer. Write clean, idiomatic, and runnable {language} code for the user's request. If possible, include comments and best practices. Generate complete, working code that can be run immediately. If the user provides a file or other context, use it as a reference. If the code is for a script or app, make it as self-contained as possible.8680 unmodified lines# Initialize Gradio documentation systeminitialize_gradio_docs()# Initialize ComfyUI documentation systeminitialize_comfyui_docs()# Clean up any orphaned temporary files from previous runscleanup_all_temp_media_on_startup()
app.py+181-16