akhaliq HF Staff commited on
Commit
225aa4f
Β·
1 Parent(s): 06ef08c

update system prompt comfy

Browse files
Files changed (1) hide show
  1. app.py +181 -16
app.py CHANGED
@@ -69,6 +69,16 @@ GRADIO_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not
69
  _gradio_docs_content: str | None = None
70
  _gradio_docs_last_fetched: Optional[datetime] = None
71
 
 
 
 
 
 
 
 
 
 
 
72
  def fetch_gradio_docs() -> str | None:
73
  """Fetch the latest Gradio documentation from llms.txt"""
74
  try:
@@ -79,6 +89,16 @@ def fetch_gradio_docs() -> str | None:
79
  print(f"Warning: Failed to fetch Gradio docs from {GRADIO_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:
@@ -131,6 +151,26 @@ def save_gradio_docs_cache(content: str):
131
  except Exception as e:
132
  print(f"Warning: Failed to save Gradio docs cache: {e}")
133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  def get_last_update_time() -> Optional[datetime]:
135
  """Get the last update time from file"""
136
  try:
@@ -146,6 +186,11 @@ def should_update_gradio_docs() -> bool:
146
  # Only update if we don't have cached content (first run or cache deleted)
147
  return not os.path.exists(GRADIO_DOCS_CACHE_FILE)
148
 
 
 
 
 
 
149
  def force_update_gradio_docs():
150
  """
151
  Force an update of Gradio documentation (useful when app is updated).
@@ -171,6 +216,31 @@ def force_update_gradio_docs():
171
  print("❌ Failed to update Gradio documentation")
172
  return False
173
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  def get_gradio_docs_content() -> str:
175
  """Get the current Gradio documentation content, updating if necessary"""
176
  global _gradio_docs_content, _gradio_docs_last_fetched
@@ -214,6 +284,49 @@ def get_gradio_docs_content() -> str:
214
 
215
  return _gradio_docs_content or ""
216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  def update_gradio_system_prompts():
218
  """Update the global Gradio system prompts with latest documentation"""
219
  global GRADIO_SYSTEM_PROMPT, GRADIO_SYSTEM_PROMPT_WITH_SEARCH
@@ -766,6 +879,55 @@ This reference is automatically synced from https://www.gradio.app/llms.txt to e
766
  GRADIO_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"
767
  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"
768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
769
  # Initialize Gradio documentation on startup
770
  def initialize_gradio_docs():
771
  """Initialize Gradio documentation on application startup"""
@@ -778,6 +940,18 @@ def initialize_gradio_docs():
778
  except Exception as e:
779
  print(f"Warning: Failed to initialize Gradio documentation: {e}")
780
 
 
 
 
 
 
 
 
 
 
 
 
 
781
  # Configuration
782
  HTML_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 FILE
783
 
@@ -1226,23 +1400,11 @@ GRADIO_SYSTEM_PROMPT_WITH_SEARCH = ""
1226
 
1227
  # All Gradio API documentation is now dynamically loaded from https://www.gradio.app/llms.txt
1228
 
1229
- JSON_SYSTEM_PROMPT = """You are an expert JSON developer. Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:
1230
- - Use double quotes for strings
1231
- - No trailing commas
1232
- - Proper nesting and structure
1233
- - Valid data types (string, number, boolean, null, object, array)
1234
-
1235
- 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."""
1236
-
1237
- 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.
1238
-
1239
- Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:
1240
- - Use double quotes for strings
1241
- - No trailing commas
1242
- - Proper nesting and structure
1243
- - Valid data types (string, number, boolean, null, object, array)
1244
 
1245
- 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."""
1246
 
1247
  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.
1248
 
@@ -9929,6 +10091,9 @@ if __name__ == "__main__":
9929
  # Initialize Gradio documentation system
9930
  initialize_gradio_docs()
9931
 
 
 
 
9932
  # Clean up any orphaned temporary files from previous runs
9933
  cleanup_all_temp_media_on_startup()
9934
 
 
69
  _gradio_docs_content: str | None = None
70
  _gradio_docs_last_fetched: Optional[datetime] = None
71
 
72
+ # ComfyUI Documentation Auto-Update System
73
+ COMFYUI_LLMS_TXT_URL = "https://docs.comfy.org/llms.txt"
74
+ COMFYUI_DOCS_CACHE_FILE = ".comfyui_docs_cache.txt"
75
+ COMFYUI_DOCS_LAST_UPDATE_FILE = ".comfyui_docs_last_update.txt"
76
+ COMFYUI_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer
77
+
78
+ # Global variable to store the current ComfyUI documentation
79
+ _comfyui_docs_content: str | None = None
80
+ _comfyui_docs_last_fetched: Optional[datetime] = None
81
+
82
  def fetch_gradio_docs() -> str | None:
83
  """Fetch the latest Gradio documentation from llms.txt"""
84
  try:
 
89
  print(f"Warning: Failed to fetch Gradio docs from {GRADIO_LLMS_TXT_URL}: {e}")
90
  return None
91
 
92
+ def fetch_comfyui_docs() -> str | None:
93
+ """Fetch the latest ComfyUI documentation from llms.txt"""
94
+ try:
95
+ response = requests.get(COMFYUI_LLMS_TXT_URL, timeout=10)
96
+ response.raise_for_status()
97
+ return response.text
98
+ except Exception as e:
99
+ print(f"Warning: Failed to fetch ComfyUI docs from {COMFYUI_LLMS_TXT_URL}: {e}")
100
+ return None
101
+
102
  def filter_problematic_instructions(content: str) -> str:
103
  """Filter out problematic instructions that cause LLM to stop generation prematurely"""
104
  if not content:
 
151
  except Exception as e:
152
  print(f"Warning: Failed to save Gradio docs cache: {e}")
153
 
154
+ def load_comfyui_docs_cache() -> str | None:
155
+ """Load ComfyUI documentation from cache file"""
156
+ try:
157
+ if os.path.exists(COMFYUI_DOCS_CACHE_FILE):
158
+ with open(COMFYUI_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:
159
+ return f.read()
160
+ except Exception as e:
161
+ print(f"Warning: Failed to load cached ComfyUI docs: {e}")
162
+ return None
163
+
164
+ def save_comfyui_docs_cache(content: str):
165
+ """Save ComfyUI documentation to cache file"""
166
+ try:
167
+ with open(COMFYUI_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:
168
+ f.write(content)
169
+ with open(COMFYUI_DOCS_LAST_UPDATE_FILE, 'w', encoding='utf-8') as f:
170
+ f.write(datetime.now().isoformat())
171
+ except Exception as e:
172
+ print(f"Warning: Failed to save ComfyUI docs cache: {e}")
173
+
174
  def get_last_update_time() -> Optional[datetime]:
175
  """Get the last update time from file"""
176
  try:
 
186
  # Only update if we don't have cached content (first run or cache deleted)
187
  return not os.path.exists(GRADIO_DOCS_CACHE_FILE)
188
 
189
+ def should_update_comfyui_docs() -> bool:
190
+ """Check if ComfyUI documentation should be updated"""
191
+ # Only update if we don't have cached content (first run or cache deleted)
192
+ return not os.path.exists(COMFYUI_DOCS_CACHE_FILE)
193
+
194
  def force_update_gradio_docs():
195
  """
196
  Force an update of Gradio documentation (useful when app is updated).
 
216
  print("❌ Failed to update Gradio documentation")
217
  return False
218
 
219
+ def force_update_comfyui_docs():
220
+ """
221
+ Force an update of ComfyUI documentation (useful when app is updated).
222
+
223
+ To manually refresh docs, you can call this function or simply delete the cache file:
224
+ rm .comfyui_docs_cache.txt && restart the app
225
+ """
226
+ global _comfyui_docs_content, _comfyui_docs_last_fetched
227
+
228
+ print("πŸ”„ Forcing ComfyUI documentation update...")
229
+ latest_content = fetch_comfyui_docs()
230
+
231
+ if latest_content:
232
+ # Filter out problematic instructions that cause early termination
233
+ filtered_content = filter_problematic_instructions(latest_content)
234
+ _comfyui_docs_content = filtered_content
235
+ _comfyui_docs_last_fetched = datetime.now()
236
+ save_comfyui_docs_cache(filtered_content)
237
+ update_json_system_prompts()
238
+ print("βœ… ComfyUI documentation updated successfully")
239
+ return True
240
+ else:
241
+ print("❌ Failed to update ComfyUI documentation")
242
+ return False
243
+
244
  def get_gradio_docs_content() -> str:
245
  """Get the current Gradio documentation content, updating if necessary"""
246
  global _gradio_docs_content, _gradio_docs_last_fetched
 
284
 
285
  return _gradio_docs_content or ""
286
 
287
+ def get_comfyui_docs_content() -> str:
288
+ """Get the current ComfyUI documentation content, updating if necessary"""
289
+ global _comfyui_docs_content, _comfyui_docs_last_fetched
290
+
291
+ # Check if we need to update
292
+ if (_comfyui_docs_content is None or
293
+ _comfyui_docs_last_fetched is None or
294
+ should_update_comfyui_docs()):
295
+
296
+ print("Updating ComfyUI documentation...")
297
+
298
+ # Try to fetch latest content
299
+ latest_content = fetch_comfyui_docs()
300
+
301
+ if latest_content:
302
+ # Filter out problematic instructions that cause early termination
303
+ filtered_content = filter_problematic_instructions(latest_content)
304
+ _comfyui_docs_content = filtered_content
305
+ _comfyui_docs_last_fetched = datetime.now()
306
+ save_comfyui_docs_cache(filtered_content)
307
+ print("βœ… ComfyUI documentation updated successfully")
308
+ else:
309
+ # Fallback to cached content
310
+ cached_content = load_comfyui_docs_cache()
311
+ if cached_content:
312
+ _comfyui_docs_content = cached_content
313
+ _comfyui_docs_last_fetched = datetime.now()
314
+ print("⚠️ Using cached ComfyUI documentation (network fetch failed)")
315
+ else:
316
+ # Fallback to minimal content
317
+ _comfyui_docs_content = """
318
+ # ComfyUI API Reference (Offline Fallback)
319
+
320
+ This is a minimal fallback when documentation cannot be fetched.
321
+ Please check your internet connection for the latest API reference.
322
+
323
+ Basic ComfyUI workflow structure: nodes, connections, inputs, outputs.
324
+ Use CheckpointLoaderSimple, CLIPTextEncode, KSampler for basic workflows.
325
+ """
326
+ print("❌ Using minimal fallback documentation")
327
+
328
+ return _comfyui_docs_content or ""
329
+
330
  def update_gradio_system_prompts():
331
  """Update the global Gradio system prompts with latest documentation"""
332
  global GRADIO_SYSTEM_PROMPT, GRADIO_SYSTEM_PROMPT_WITH_SEARCH
 
879
  GRADIO_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"
880
  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"
881
 
882
+ def update_json_system_prompts():
883
+ """Update the global JSON system prompts with latest ComfyUI documentation"""
884
+ global JSON_SYSTEM_PROMPT, JSON_SYSTEM_PROMPT_WITH_SEARCH
885
+
886
+ docs_content = get_comfyui_docs_content()
887
+
888
+ # Base system prompt
889
+ base_prompt = """You are an expert JSON developer. Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:
890
+ - Use double quotes for strings
891
+ - No trailing commas
892
+ - Proper nesting and structure
893
+ - Valid data types (string, number, boolean, null, object, array)
894
+
895
+ 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.
896
+
897
+ """
898
+
899
+ # Search-enabled system prompt
900
+ search_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.
901
+
902
+ Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:
903
+ - Use double quotes for strings
904
+ - No trailing commas
905
+ - Proper nesting and structure
906
+ - Valid data types (string, number, boolean, null, object, array)
907
+
908
+ 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.
909
+
910
+ """
911
+
912
+ # Add ComfyUI documentation if available
913
+ if docs_content.strip():
914
+ comfyui_section = f"""
915
+ ## ComfyUI Reference Documentation
916
+
917
+ When generating JSON data related to ComfyUI workflows, nodes, or configurations, use this reference:
918
+
919
+ {docs_content}
920
+
921
+ This reference is automatically synced from https://docs.comfy.org/llms.txt to ensure accuracy.
922
+
923
+ """
924
+ base_prompt += comfyui_section
925
+ search_prompt += comfyui_section
926
+
927
+ # Update the prompts
928
+ JSON_SYSTEM_PROMPT = base_prompt
929
+ JSON_SYSTEM_PROMPT_WITH_SEARCH = search_prompt
930
+
931
  # Initialize Gradio documentation on startup
932
  def initialize_gradio_docs():
933
  """Initialize Gradio documentation on application startup"""
 
940
  except Exception as e:
941
  print(f"Warning: Failed to initialize Gradio documentation: {e}")
942
 
943
+ # Initialize ComfyUI documentation on startup
944
+ def initialize_comfyui_docs():
945
+ """Initialize ComfyUI documentation on application startup"""
946
+ try:
947
+ update_json_system_prompts()
948
+ if should_update_comfyui_docs():
949
+ print("πŸš€ ComfyUI documentation system initialized (fetched fresh content)")
950
+ else:
951
+ print("πŸš€ ComfyUI documentation system initialized (using cached content)")
952
+ except Exception as e:
953
+ print(f"Warning: Failed to initialize ComfyUI documentation: {e}")
954
+
955
  # Configuration
956
  HTML_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 FILE
957
 
 
1400
 
1401
  # All Gradio API documentation is now dynamically loaded from https://www.gradio.app/llms.txt
1402
 
1403
+ # JSON system prompts will be dynamically populated by update_json_system_prompts()
1404
+ JSON_SYSTEM_PROMPT = ""
1405
+ JSON_SYSTEM_PROMPT_WITH_SEARCH = ""
 
 
 
 
 
 
 
 
 
 
 
 
1406
 
1407
+ # All ComfyUI API documentation is now dynamically loaded from https://docs.comfy.org/llms.txt
1408
 
1409
  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.
1410
 
 
10091
  # Initialize Gradio documentation system
10092
  initialize_gradio_docs()
10093
 
10094
+ # Initialize ComfyUI documentation system
10095
+ initialize_comfyui_docs()
10096
+
10097
  # Clean up any orphaned temporary files from previous runs
10098
  cleanup_all_temp_media_on_startup()
10099