Spaces:
Runtime error
Runtime error
cleanup
Browse filesFiles changed (11)
- anycoder_app/__init__.pyDeleted-27
- anycoder_app/agent.pyDeleted-234
- anycoder_app/config.pyDeleted-190
- anycoder_app/deploy.pyDeleted
- anycoder_app/docs_manager.pyDeleted-1484
- anycoder_app/models.pyDeleted-361
- anycoder_app/parsers.pyDeleted-1111
- anycoder_app/prompts.pyDeleted-817
- anycoder_app/themes.pyDeleted-257
- anycoder_app/ui.pyDeleted
- app.py.backupDeleted
123456789101112131415161718192021222324252627"""AnyCoder - AI Code Generator PackageModular structure for better code organization and maintainability."""
__version__ = "1.0.0"
from . import configfrom . import promptsfrom . import docs_managerfrom . import modelsfrom . import parsersfrom . import deployfrom . import themesfrom . import ui
__all__ = [ "config", "prompts", "docs_manager", "models", "parsers", "deploy", "themes", "ui",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234"""Agent functionality for interactive code generation with follow-up questions and task planning."""import osfrom typing import Dict, List, Optional, Tuple, Generatorimport gradio as gr
from .models import ( get_inference_client, get_real_model_id, history_to_messages, history_to_chatbot_messages, strip_thinking_tags)from .deploy import generation_code
def agent_generate_with_questions( query: Optional[str], setting: Dict[str, str], history: List, current_model: Dict, language: str, provider: str, profile: Optional[gr.OAuthProfile] = None, token: Optional[gr.OAuthToken] = None, max_questions: int = 3) -> Generator[Tuple[List, List], None, None]: """ Agent that asks follow-up questions, creates a task list, and generates code. Args: query: Initial user request setting: System settings history: Conversation history current_model: Selected model configuration language: Target programming language/framework provider: Model provider profile: User OAuth profile token: User OAuth token max_questions: Maximum number of follow-up questions to ask Yields: Tuples of (history, chatbot_messages) at each step """ if not query or not query.strip(): return # Initialize history with user's initial query current_history = history + [[query, ""]] # Step 1: Agent analyzes the request and asks follow-up questions agent_system_prompt = """You are a helpful coding assistant that helps users clarify their requirements before generating code.
Your task is to:1. Analyze the user's request2. Ask 1-3 clarifying questions to better understand their needs3. Focus on important details like: - Target audience and use case - Specific features or functionality needed - Design preferences (colors, layout, style) - Data sources or APIs to integrate - Performance or scalability requirements
Output ONLY the questions, numbered 1, 2, 3, etc. Keep questions concise and focused.Do not generate code yet - just ask the questions."""
# Get LLM client client = get_inference_client(current_model.get('model_id', 'Qwen/Qwen2.5-Coder-32B-Instruct'), provider) model_id = get_real_model_id(current_model.get('model_id', 'Qwen/Qwen2.5-Coder-32B-Instruct')) # Prepare messages for follow-up questions messages = [ {'role': 'system', 'content': agent_system_prompt}, {'role': 'user', 'content': f"User wants to create: {query}\n\nLanguage/Framework: {language}\n\nAsk clarifying questions."} ] # Generate follow-up questions questions_response = "" try: # Try to use the client (works for both InferenceClient and OpenAI-compatible clients) stream = client.chat.completions.create( model=model_id, messages=messages, temperature=0.7, max_tokens=500, stream=True ) for chunk in stream: if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content: questions_response += chunk.choices[0].delta.content # Update display in real-time temp_history = current_history[:-1] + [[query, f"🤔 **Analyzing your request...**\n\n{questions_response}"]] yield (temp_history, history_to_chatbot_messages(temp_history)) except Exception as e: error_msg = f"❌ Error asking follow-up questions: {str(e)}" temp_history = current_history[:-1] + [[query, error_msg]] yield (temp_history, history_to_chatbot_messages(temp_history)) return # Update history with agent's questions current_history[-1][1] = f"🤔 **Let me ask you a few questions to better understand your needs:**\n\n{questions_response}\n\n💬 Please answer these questions in your next message." yield (current_history, history_to_chatbot_messages(current_history)) # Wait for user response (this will be handled by the UI) # For now, we'll return and let the user respond, then continue in the next call return
def agent_process_answers_and_generate( user_answers: str, original_query: str, questions: str, setting: Dict[str, str], history: List, current_model: Dict, language: str, provider: str, profile: Optional[gr.OAuthProfile] = None, token: Optional[gr.OAuthToken] = None, code_output=None, history_output=None, history_state=None) -> Generator: """ Process user's answers, create task list, and generate code. Args: user_answers: User's responses to the questions original_query: Original user request questions: Agent's questions setting: System settings history: Conversation history current_model: Selected model configuration language: Target programming language/framework provider: Model provider profile: User OAuth profile token: User OAuth token code_output: Code output component history_output: History output component history_state: History state Yields: Updates to code output and history """ # Step 2: Create task list based on answers task_planning_prompt = f"""Based on the user's request and their answers, create a detailed task list for implementing the solution.
Original Request: {original_query}
Questions Asked:{questions}
User's Answers:{user_answers}
Create a numbered task list with 5-8 specific, actionable tasks. Each task should be clear and focused.Start with "📋 **Task List:**" and then list the tasks."""
client = get_inference_client(current_model.get('model_id', 'Qwen/Qwen2.5-Coder-32B-Instruct'), provider) model_id = get_real_model_id(current_model.get('model_id', 'Qwen/Qwen2.5-Coder-32B-Instruct')) messages = [ {'role': 'system', 'content': 'You are a helpful coding assistant creating a task plan.'}, {'role': 'user', 'content': task_planning_prompt} ] # Generate task list task_list = "" try: stream = client.chat.completions.create( model=model_id, messages=messages, temperature=0.7, max_tokens=800, stream=True ) for chunk in stream: if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content: task_list += chunk.choices[0].delta.content # Update display temp_history = history + [[user_answers, f"📋 **Creating task list...**\n\n{task_list}"]] yield { history_state: temp_history, history_output: history_to_chatbot_messages(temp_history) } except Exception as e: error_msg = f"❌ Error creating task list: {str(e)}" temp_history = history + [[user_answers, error_msg]] yield { history_state: temp_history, history_output: history_to_chatbot_messages(temp_history) } return # Update history with task list updated_history = history + [[user_answers, task_list]] yield { history_state: updated_history, history_output: history_to_chatbot_messages(updated_history) } # Step 3: Generate code based on refined requirements refined_query = f"""{original_query}
Additional Requirements (based on follow-up):{user_answers}
Task List:{task_list}
Please implement the above requirements following the task list.""" # Add a message indicating code generation is starting code_gen_start_history = updated_history + [["[System]", "🚀 **Starting code generation based on your requirements...**"]] yield { history_state: code_gen_start_history, history_output: history_to_chatbot_messages(code_gen_start_history) } # Use the existing generation_code function for actual code generation # We need to pass the refined query and updated history for result in generation_code( refined_query, setting, updated_history, current_model, language, provider, profile, token, code_output, history_output, history_state ): yield result
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""Configuration constants for AnyCoder application."""import osfrom datetime import datetimefrom typing import Optional
# Gradio supported languages for syntax highlightingGRADIO_SUPPORTED_LANGUAGES = [ "python", "json", "html", "javascript"]
# Search/Replace ConstantsSEARCH_START = "<<<<<<< SEARCH"DIVIDER = "======="REPLACE_END = ">>>>>>> REPLACE"
# Gradio Documentation Auto-Update SystemGRADIO_LLMS_TXT_URL = "https://www.gradio.app/llms.txt"GRADIO_DOCS_CACHE_FILE = ".gradio_docs_cache.txt"GRADIO_DOCS_LAST_UPDATE_FILE = ".gradio_docs_last_update.txt"GRADIO_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer
# Global variable to store the current Gradio documentation_gradio_docs_content: Optional[str] = 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: Optional[str] = None_comfyui_docs_last_fetched: Optional[datetime] = None
# FastRTC Documentation Auto-Update SystemFASTRTC_LLMS_TXT_URL = "https://fastrtc.org/llms.txt"FASTRTC_DOCS_CACHE_FILE = ".fastrtc_docs_cache.txt"FASTRTC_DOCS_LAST_UPDATE_FILE = ".fastrtc_docs_last_update.txt"FASTRTC_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer
# Global variable to store the current FastRTC documentation_fastrtc_docs_content: Optional[str] = None_fastrtc_docs_last_fetched: Optional[datetime] = None
# Available Models ConfigurationAVAILABLE_MODELS = [ { "name": "Gemini 3.0 Pro", "id": "gemini-3.0-pro", "description": "Google Gemini 3.0 Pro via Poe with advanced reasoning" }, { "name": "DeepSeek V3.2-Exp", "id": "deepseek-ai/DeepSeek-V3.2-Exp", "description": "DeepSeek V3.2 Experimental model for cutting-edge code generation and reasoning" }, { "name": "DeepSeek R1", "id": "deepseek-ai/DeepSeek-R1-0528", "description": "DeepSeek R1 model for code generation" }, { "name": "GLM-4.6", "id": "zai-org/GLM-4.6", "description": "GLM-4.6 model for advanced code generation and general tasks" }, { "name": "Gemini Flash Latest", "id": "gemini-flash-latest", "description": "Google Gemini Flash Latest model via native Gemini API" }, { "name": "Gemini Flash Lite Latest", "id": "gemini-flash-lite-latest", "description": "Google Gemini Flash Lite Latest model via OpenAI-compatible API" }, { "name": "GPT-5", "id": "gpt-5", "description": "OpenAI GPT-5 model for advanced code generation and general tasks" }, { "name": "GPT-5.1", "id": "gpt-5.1", "description": "OpenAI GPT-5.1 model via Poe for advanced code generation and general tasks" }, { "name": "GPT-5.1 Instant", "id": "gpt-5.1-instant", "description": "OpenAI GPT-5.1 Instant model via Poe for fast responses" }, { "name": "GPT-5.1 Codex", "id": "gpt-5.1-codex", "description": "OpenAI GPT-5.1 Codex model via Poe optimized for code generation" }, { "name": "GPT-5.1 Codex Mini", "id": "gpt-5.1-codex-mini", "description": "OpenAI GPT-5.1 Codex Mini model via Poe for lightweight code generation" }, { "name": "Grok-4", "id": "grok-4", "description": "Grok-4 model via Poe (OpenAI-compatible) for advanced tasks" }, { "name": "Grok-Code-Fast-1", "id": "Grok-Code-Fast-1", "description": "Grok-Code-Fast-1 model via Poe (OpenAI-compatible) for fast code generation" }, { "name": "Claude-Opus-4.1", "id": "claude-opus-4.1", "description": "Anthropic Claude Opus 4.1 via Poe (OpenAI-compatible)" }, { "name": "Claude-Sonnet-4.5", "id": "claude-sonnet-4.5", "description": "Anthropic Claude Sonnet 4.5 via Poe (OpenAI-compatible)" }, { "name": "Claude-Haiku-4.5", "id": "claude-haiku-4.5", "description": "Anthropic Claude Haiku 4.5 via Poe (OpenAI-compatible)" }, { "name": "Qwen3 Max Preview", "id": "qwen3-max-preview", "description": "Qwen3 Max Preview model via DashScope International API" }, { "name": "MiniMax M2", "id": "MiniMaxAI/MiniMax-M2", "description": "MiniMax M2 model via HuggingFace InferenceClient with Novita provider" }, { "name": "Kimi K2 Thinking", "id": "moonshotai/Kimi-K2-Thinking", "description": "Moonshot Kimi K2 Thinking model for advanced reasoning and code generation" }, { "name": "Grok 4.1 Fast", "id": "x-ai/grok-4.1-fast", "description": "Grok 4.1 Fast model via OpenRouter for advanced code generation and reasoning" }, { "name": "Sherlock Think Alpha", "id": "openrouter/sherlock-think-alpha", "description": "Sherlock Think Alpha model via OpenRouter for advanced reasoning with thinking capabilities" }]
k2_model_name_tag = "moonshotai/Kimi-K2-Thinking"
# Default model selectionDEFAULT_MODEL_NAME = "GLM-4.6"DEFAULT_MODEL = Nonefor _m in AVAILABLE_MODELS: if _m.get("name") == DEFAULT_MODEL_NAME: DEFAULT_MODEL = _m breakif DEFAULT_MODEL is None and AVAILABLE_MODELS: DEFAULT_MODEL = AVAILABLE_MODELS[0]
# HF Inference ClientHF_TOKEN = os.getenv('HF_TOKEN')# Note: HF_TOKEN is checked at runtime when needed, not at import time
# Language choices for code generationLANGUAGE_CHOICES = [ "html", "gradio", "transformers.js", "streamlit", "comfyui", "react"]
def get_gradio_language(language): """Map composite options to a supported syntax highlighting.""" if language == "streamlit": return "python" if language == "gradio": return "python" if language == "comfyui": return "json" if language == "react": return "javascript" return language if language in GRADIO_SUPPORTED_LANGUAGES else None
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484"""Documentation management for Gradio, ComfyUI, and FastRTC.Handles fetching, caching, and updating documentation from llms.txt files."""import osimport requestsimport refrom datetime import datetime, timedeltafrom typing import Optional
from .config import ( GRADIO_LLMS_TXT_URL, GRADIO_DOCS_CACHE_FILE, GRADIO_DOCS_LAST_UPDATE_FILE, GRADIO_DOCS_UPDATE_ON_APP_UPDATE, _gradio_docs_content, _gradio_docs_last_fetched, COMFYUI_LLMS_TXT_URL, COMFYUI_DOCS_CACHE_FILE, COMFYUI_DOCS_LAST_UPDATE_FILE, COMFYUI_DOCS_UPDATE_ON_APP_UPDATE, _comfyui_docs_content, _comfyui_docs_last_fetched, FASTRTC_LLMS_TXT_URL, FASTRTC_DOCS_CACHE_FILE, FASTRTC_DOCS_LAST_UPDATE_FILE, FASTRTC_DOCS_UPDATE_ON_APP_UPDATE, _fastrtc_docs_content, _fastrtc_docs_last_fetched)from . import prompts
def fetch_gradio_docs() -> Optional[str]: """Fetch the latest Gradio documentation from llms.txt""" try: response = requests.get(GRADIO_LLMS_TXT_URL, timeout=10) response.raise_for_status() return response.text except Exception as e: print(f"Warning: Failed to fetch Gradio docs from {GRADIO_LLMS_TXT_URL}: {e}") return None
def fetch_comfyui_docs() -> Optional[str]: """Fetch the latest ComfyUI documentation from llms.txt""" try: response = requests.get(COMFYUI_LLMS_TXT_URL, timeout=10) response.raise_for_status() return response.text except Exception as e: print(f"Warning: Failed to fetch ComfyUI docs from {COMFYUI_LLMS_TXT_URL}: {e}") return None
def fetch_fastrtc_docs() -> Optional[str]: """Fetch the latest FastRTC documentation from llms.txt""" try: response = requests.get(FASTRTC_LLMS_TXT_URL, timeout=10) response.raise_for_status() return response.text except Exception as e: print(f"Warning: Failed to fetch FastRTC docs from {FASTRTC_LLMS_TXT_URL}: {e}") return None
def filter_problematic_instructions(content: str) -> str: """Filter out problematic instructions that cause LLM to stop generation prematurely""" if not content: return content # List of problematic phrases that cause early termination when LLM encounters ``` in user code problematic_patterns = [ r"Output ONLY the code inside a ``` code block, and do not include any explanations or extra text", r"output only the code inside a ```.*?``` code block", r"Always output only the.*?code.*?inside.*?```.*?```.*?block", r"Return ONLY the code inside a.*?```.*?``` code block", r"Do NOT add the language name at the top of the code output", r"do not include any explanations or extra text", r"Always output only the.*?code blocks.*?shown above, and do not include any explanations", r"Output.*?ONLY.*?code.*?inside.*?```.*?```", r"Return.*?ONLY.*?code.*?inside.*?```.*?```", r"Generate.*?ONLY.*?code.*?inside.*?```.*?```", r"Provide.*?ONLY.*?code.*?inside.*?```.*?```", ] # Remove problematic patterns filtered_content = content for pattern in problematic_patterns: # Use case-insensitive matching filtered_content = re.sub(pattern, "", filtered_content, flags=re.IGNORECASE | re.DOTALL) # Clean up any double newlines or extra whitespace left by removals filtered_content = re.sub(r'\n\s*\n\s*\n', '\n\n', filtered_content) filtered_content = re.sub(r'^\s+', '', filtered_content, flags=re.MULTILINE) return filtered_content
def load_cached_gradio_docs() -> Optional[str]: """Load cached Gradio documentation from file""" try: if os.path.exists(GRADIO_DOCS_CACHE_FILE): with open(GRADIO_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f: return f.read() except Exception as e: print(f"Warning: Failed to load cached Gradio docs: {e}") return None
def save_gradio_docs_cache(content: str): """Save Gradio documentation to cache file""" try: with open(GRADIO_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f: f.write(content) with open(GRADIO_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 Gradio docs cache: {e}")
def load_comfyui_docs_cache() -> Optional[str]: """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 None
def 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 load_fastrtc_docs_cache() -> Optional[str]: """Load FastRTC documentation from cache file""" try: if os.path.exists(FASTRTC_DOCS_CACHE_FILE): with open(FASTRTC_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f: return f.read() except Exception as e: print(f"Warning: Failed to load cached FastRTC docs: {e}") return None
def save_fastrtc_docs_cache(content: str): """Save FastRTC documentation to cache file""" try: with open(FASTRTC_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f: f.write(content) with open(FASTRTC_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 FastRTC docs cache: {e}")
def get_last_update_time() -> Optional[datetime]: """Get the last update time from file""" try: if os.path.exists(GRADIO_DOCS_LAST_UPDATE_FILE): with open(GRADIO_DOCS_LAST_UPDATE_FILE, 'r', encoding='utf-8') as f: return datetime.fromisoformat(f.read().strip()) except Exception as e: print(f"Warning: Failed to read last update time: {e}") return None
def should_update_gradio_docs() -> bool: """Check if Gradio documentation should be updated""" # 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 should_update_fastrtc_docs() -> bool: """Check if FastRTC documentation should be updated""" # Only update if we don't have cached content (first run or cache deleted) return not os.path.exists(FASTRTC_DOCS_CACHE_FILE)
def force_update_gradio_docs(): """ Force an update of Gradio documentation (useful when app is updated). To manually refresh docs, you can call this function or simply delete the cache file: rm .gradio_docs_cache.txt && restart the app """ global _gradio_docs_content, _gradio_docs_last_fetched print("🔄 Forcing Gradio documentation update...") latest_content = fetch_gradio_docs() if latest_content: # Filter out problematic instructions that cause early termination filtered_content = filter_problematic_instructions(latest_content) _gradio_docs_content = filtered_content _gradio_docs_last_fetched = datetime.now() save_gradio_docs_cache(filtered_content) update_gradio_system_prompts() print("✅ Gradio documentation updated successfully") return True else: print("❌ Failed to update Gradio documentation") return False
def 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_fetched print("🔄 Forcing ComfyUI documentation update...") latest_content = fetch_comfyui_docs() if latest_content: # Filter out problematic instructions that cause early termination filtered_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 True else: print("❌ Failed to update ComfyUI documentation") return False
def force_update_fastrtc_docs(): """ Force an update of FastRTC documentation (useful when app is updated). To manually refresh docs, you can call this function or simply delete the cache file: rm .fastrtc_docs_cache.txt && restart the app """ global _fastrtc_docs_content, _fastrtc_docs_last_fetched print("🔄 Forcing FastRTC documentation update...") latest_content = fetch_fastrtc_docs() if latest_content: # Filter out problematic instructions that cause early termination filtered_content = filter_problematic_instructions(latest_content) _fastrtc_docs_content = filtered_content _fastrtc_docs_last_fetched = datetime.now() save_fastrtc_docs_cache(filtered_content) update_gradio_system_prompts() print("✅ FastRTC documentation updated successfully") return True else: print("❌ Failed to update FastRTC documentation") return False
def get_gradio_docs_content() -> str: """Get the current Gradio documentation content, updating if necessary""" global _gradio_docs_content, _gradio_docs_last_fetched # Check if we need to update if (_gradio_docs_content is None or _gradio_docs_last_fetched is None or should_update_gradio_docs()): print("Updating Gradio documentation...") # Try to fetch latest content latest_content = fetch_gradio_docs() if latest_content: # Filter out problematic instructions that cause early termination filtered_content = filter_problematic_instructions(latest_content) _gradio_docs_content = filtered_content _gradio_docs_last_fetched = datetime.now() save_gradio_docs_cache(filtered_content) print("✅ Gradio documentation updated successfully") else: # Fallback to cached content cached_content = load_cached_gradio_docs() if cached_content: _gradio_docs_content = cached_content _gradio_docs_last_fetched = datetime.now() print("⚠️ Using cached Gradio documentation (network fetch failed)") else: # Fallback to minimal content _gradio_docs_content = """ # Gradio 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 Gradio components: Button, Textbox, Slider, Image, Audio, Video, File, etc. Use gr.Blocks() for custom layouts and gr.Interface() for simple apps. """ print("❌ Using minimal fallback documentation") return _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 update if (_comfyui_docs_content is None or _comfyui_docs_last_fetched is None or should_update_comfyui_docs()): print("Updating ComfyUI documentation...") # Try to fetch latest content latest_content = fetch_comfyui_docs() if latest_content: # Filter out problematic instructions that cause early termination filtered_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 content cached_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 get_fastrtc_docs_content() -> str: """Get the current FastRTC documentation content, updating if necessary""" global _fastrtc_docs_content, _fastrtc_docs_last_fetched # Check if we need to update if (_fastrtc_docs_content is None or _fastrtc_docs_last_fetched is None or should_update_fastrtc_docs()): print("Updating FastRTC documentation...") # Try to fetch latest content latest_content = fetch_fastrtc_docs() if latest_content: # Filter out problematic instructions that cause early termination filtered_content = filter_problematic_instructions(latest_content) _fastrtc_docs_content = filtered_content _fastrtc_docs_last_fetched = datetime.now() save_fastrtc_docs_cache(filtered_content) print("✅ FastRTC documentation updated successfully") else: # Fallback to cached content cached_content = load_fastrtc_docs_cache() if cached_content: _fastrtc_docs_content = cached_content _fastrtc_docs_last_fetched = datetime.now() print("⚠️ Using cached FastRTC documentation (network fetch failed)") else: # Fallback to minimal content _fastrtc_docs_content = """ # FastRTC 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 FastRTC usage: Stream class, handlers, real-time audio/video processing. Use Stream(handler, modality, mode) for real-time communication apps. """ print("❌ Using minimal fallback documentation") return _fastrtc_docs_content or ""
def update_gradio_system_prompts(): """Update the global Gradio system prompts with latest documentation""" docs_content = get_gradio_docs_content() fastrtc_content = get_fastrtc_docs_content() # Base system prompt base_prompt = """You are an expert Gradio developer. Create a complete, working Gradio application based on the user's request. Generate all necessary code to make the application functional and runnable.
🚨 CRITICAL OUTPUT RULES:- DO NOT use <think> tags or thinking blocks in your output- DO NOT use [TOOL_CALL] or any tool call markers- Generate ONLY the requested code files and requirements.txt- No explanatory text outside the code blocks
## 🎯 Working with Imported Model Code
**CRITICAL: If the user has imported model code in the conversation history (InferenceClient, transformers, diffusers), you MUST integrate it into your Gradio application!**
**For InferenceClient Code (HuggingFace Inference API):**- DO NOT just copy the standalone inference code- Create a complete Gradio application that wraps the inference code- Use `gr.ChatInterface()` for chat models or appropriate interface for other tasks- Extract the model name from the imported code- Implement proper streaming if the model supports it- Handle conversation history correctly
**Example Structure for Chatbot:**```pythonimport gradio as grimport osfrom huggingface_hub import InferenceClient
# Use the InferenceClient configuration from imported codeclient = InferenceClient(api_key=os.environ["HF_TOKEN"])
def respond(message, history): # Build messages from history messages = [{"role": "system", "content": "You are a helpful assistant."}] for user_msg, assistant_msg in history: messages.append({"role": "user", "content": user_msg}) messages.append({"role": "assistant", "content": assistant_msg}) messages.append({"role": "user", "content": message}) # Call the model (use model name from imported code) response = "" for chunk in client.chat.completions.create( model="MODEL_NAME_FROM_IMPORTED_CODE", messages=messages, stream=True, max_tokens=1024, ): if chunk.choices[0].delta.content: response += chunk.choices[0].delta.content yield response
demo = gr.ChatInterface(respond, title="Chatbot", description="Chat with the model")demo.launch()```
**For Transformers/Diffusers Code:**- Extract model loading and inference logic- Wrap it in appropriate Gradio interface- For chat models: use gr.ChatInterface- For image generation: use gr.Interface with image output- For other tasks: choose appropriate interface type- Include proper error handling and loading states
**Key Requirements:**1. ✅ ALWAYS create a complete Gradio application, not just inference code2. ✅ Extract model configuration from imported code3. ✅ Use appropriate Gradio interface for the task4. ✅ Include demo.launch() at the end5. ✅ Add requirements.txt with necessary dependencies
## Multi-File Application Structure
When creating complex Gradio applications, organize your code into multiple files for better maintainability:
**File Organization:**- `app.py` - Main application entry point with Gradio interface- `utils.py` - Utility functions and helpers- `models.py` - Model loading and inference functions- `config.py` - Configuration and constants- `requirements.txt` - Python dependencies- Additional modules as needed (e.g., `data_processing.py`, `ui_components.py`)
**🚨 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 process- Only generate the code files listed above
**Output Format for Multi-File Apps:**When generating multi-file applications, use this exact format:
```=== app.py ===[main application code]
=== utils.py ===[utility functions]
=== requirements.txt ===[dependencies]```
**🚨 CRITICAL: Always Generate requirements.txt for New Applications**- ALWAYS include requirements.txt when creating new Gradio applications- Generate comprehensive, production-ready dependencies based on your code- Include not just direct imports but also commonly needed companion packages- Use correct PyPI package names (e.g., PIL → Pillow, sklearn → scikit-learn)- For diffusers: use `git+https://github.com/huggingface/diffusers`- For transformers: use `git+https://github.com/huggingface/transformers`- Include supporting packages (accelerate, torch, tokenizers, etc.) when using ML libraries- Your requirements.txt should ensure the application works smoothly in production
**🚨 CRITICAL: requirements.txt Formatting Rules**- Output ONLY plain text package names, one per line- Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)- Do NOT add explanatory text or descriptions- Do NOT wrap in code blocks- Just raw package names as they would appear in a real requirements.txt file- Example of CORRECT format: gradio torch transformers- Example of INCORRECT format (DO NOT DO THIS): ``` gradio # For web interface **Core dependencies:** - torch ```
**Single vs Multi-File Decision:**- Use single file for simple applications (< 100 lines) - but still generate requirements.txt if dependencies exist- Use multi-file structure for complex applications with: - Multiple models or processing pipelines - Extensive utility functions - Complex UI with many components - Data processing workflows - When user specifically requests modular structure
🚨 IMPORTANT: If the user is asking to use external APIs (like OpenRouter, OpenAI API, Hugging Face Inference API, etc.), DO NOT use @spaces.GPU decorators or any ZeroGPU features. External APIs handle the model inference remotely, so GPU allocation on the Spaces instance is not needed.
🚨 CRITICAL REQUIREMENT: If the user provides ANY diffusion model code (FLUX, Stable Diffusion, etc.) that runs locally (not via API), you MUST implement ZeroGPU ahead-of-time (AoT) compilation. This is mandatory and provides 1.3x-1.8x performance improvements. Do not create basic Gradio apps without AoT optimization for diffusion models.
## ZeroGPU Integration (MANDATORY)
ALWAYS use ZeroGPU for GPU-dependent functions in Gradio apps:
1. Import the spaces module: `import spaces`2. Decorate GPU-dependent functions with `@spaces.GPU`3. Specify appropriate duration based on expected runtime: - Quick inference (< 30s): `@spaces.GPU(duration=30)` - Standard generation (30-60s): `@spaces.GPU` (default 60s) - Complex generation (60-120s): `@spaces.GPU(duration=120)` - Heavy processing (120-180s): `@spaces.GPU(duration=180)`
Example usage:```pythonimport spacesfrom diffusers import DiffusionPipeline
pipe = DiffusionPipeline.from_pretrained(...)pipe.to('cuda')
@spaces.GPU(duration=120)def generate(prompt): return pipe(prompt).images
gr.Interface( fn=generate, inputs=gr.Text(), outputs=gr.Gallery(),).launch()```
Duration Guidelines:- Shorter durations improve queue priority for users- Text-to-image: typically 30-60 seconds- Image-to-image: typically 20-40 seconds - Video generation: typically 60-180 seconds- Audio/music generation: typically 30-90 seconds- Model loading + inference: add 10-30s buffer- AoT compilation during startup: use @spaces.GPU(duration=1500) for maximum allowed duration
Functions that typically need @spaces.GPU:- Image generation (text-to-image, image-to-image)- Video generation- Audio/music generation- Model inference with transformers, diffusers- Any function using .to('cuda') or GPU operations
## CRITICAL: Use ZeroGPU AoT Compilation for ALL Diffusion Models
FOR ANY DIFFUSION MODEL (FLUX, Stable Diffusion, etc.), YOU MUST IMPLEMENT AHEAD-OF-TIME COMPILATION.This is NOT optional - it provides 1.3x-1.8x speedup and is essential for production ZeroGPU Spaces.
ALWAYS implement this pattern for diffusion models:
### MANDATORY: Basic AoT Compilation PatternYOU MUST USE THIS EXACT PATTERN for any diffusion model (FLUX, Stable Diffusion, etc.):
1. ALWAYS add AoT compilation function with @spaces.GPU(duration=1500)2. ALWAYS use spaces.aoti_capture to capture inputs3. ALWAYS use torch.export.export to export the transformer4. ALWAYS use spaces.aoti_compile to compile5. ALWAYS use spaces.aoti_apply to apply to pipeline
### Required AoT Implementation```pythonimport spacesimport torchfrom diffusers import DiffusionPipeline
MODEL_ID = 'black-forest-labs/FLUX.1-dev'pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)pipe.to('cuda')
@spaces.GPU(duration=1500) # Maximum duration allowed during startupdef compile_transformer(): # 1. Capture example inputs with spaces.aoti_capture(pipe.transformer) as call: pipe("arbitrary example prompt") # 2. Export the model exported = torch.export.export( pipe.transformer, args=call.args, kwargs=call.kwargs, ) # 3. Compile the exported model return spaces.aoti_compile(exported)
# 4. Apply compiled model to pipelinecompiled_transformer = compile_transformer()spaces.aoti_apply(compiled_transformer, pipe.transformer)
@spaces.GPUdef generate(prompt): return pipe(prompt).images```
### Advanced Optimizations
#### FP8 Quantization (Additional 1.2x speedup on H200)```pythonfrom torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
@spaces.GPU(duration=1500)def compile_transformer_with_quantization(): # Quantize before export for FP8 speedup quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig()) with spaces.aoti_capture(pipe.transformer) as call: pipe("arbitrary example prompt") exported = torch.export.export( pipe.transformer, args=call.args, kwargs=call.kwargs, ) return spaces.aoti_compile(exported)```
#### Dynamic Shapes (Variable input sizes)```pythonfrom torch.utils._pytree import tree_map
@spaces.GPU(duration=1500)def compile_transformer_dynamic(): with spaces.aoti_capture(pipe.transformer) as call: pipe("arbitrary example prompt") # Define dynamic dimension ranges (model-dependent) transformer_hidden_dim = torch.export.Dim('hidden', min=4096, max=8212) # Map argument names to dynamic dimensions transformer_dynamic_shapes = { "hidden_states": {1: transformer_hidden_dim}, "img_ids": {0: transformer_hidden_dim}, } # Create dynamic shapes structure dynamic_shapes = tree_map(lambda v: None, call.kwargs) dynamic_shapes.update(transformer_dynamic_shapes) exported = torch.export.export( pipe.transformer, args=call.args, kwargs=call.kwargs, dynamic_shapes=dynamic_shapes, ) return spaces.aoti_compile(exported)```
#### Multi-Compile for Different Resolutions```python@spaces.GPU(duration=1500)def compile_multiple_resolutions(): compiled_models = {} resolutions = [(512, 512), (768, 768), (1024, 1024)] for width, height in resolutions: # Capture inputs for specific resolution with spaces.aoti_capture(pipe.transformer) as call: pipe(f"test prompt {width}x{height}", width=width, height=height) exported = torch.export.export( pipe.transformer, args=call.args, kwargs=call.kwargs, ) compiled_models[f"{width}x{height}"] = spaces.aoti_compile(exported) return compiled_models
# Usage with resolution dispatchcompiled_models = compile_multiple_resolutions()
@spaces.GPUdef generate_with_resolution(prompt, width=1024, height=1024): resolution_key = f"{width}x{height}" if resolution_key in compiled_models: # Temporarily apply the right compiled model spaces.aoti_apply(compiled_models[resolution_key], pipe.transformer) return pipe(prompt, width=width, height=height).images```
#### FlashAttention-3 Integration```pythonfrom kernels import get_kernel
# Load pre-built FA3 kernel compatible with H200try: vllm_flash_attn3 = get_kernel("kernels-community/vllm-flash-attn3") print("✅ FlashAttention-3 kernel loaded successfully")except Exception as e: print(f"⚠️ FlashAttention-3 not available: {e}")
# Custom attention processor exampleclass FlashAttention3Processor: def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None): # Use FA3 kernel for attention computation return vllm_flash_attn3(hidden_states, encoder_hidden_states, attention_mask)
# Apply FA3 processor to modelif 'vllm_flash_attn3' in locals(): for name, module in pipe.transformer.named_modules(): if hasattr(module, 'processor'): module.processor = FlashAttention3Processor()```
### Complete Optimized Example```pythonimport spacesimport torchfrom diffusers import DiffusionPipelinefrom torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
MODEL_ID = 'black-forest-labs/FLUX.1-dev'pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)pipe.to('cuda')
@spaces.GPU(duration=1500)def compile_optimized_transformer(): # Apply FP8 quantization quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig()) # Capture inputs with spaces.aoti_capture(pipe.transformer) as call: pipe("optimization test prompt") # Export and compile exported = torch.export.export( pipe.transformer, args=call.args, kwargs=call.kwargs, ) return spaces.aoti_compile(exported)
# Compile during startupcompiled_transformer = compile_optimized_transformer()spaces.aoti_apply(compiled_transformer, pipe.transformer)
@spaces.GPUdef generate(prompt): return pipe(prompt).images```
**Expected Performance Gains:**- Basic AoT: 1.3x-1.8x speedup- + FP8 Quantization: Additional 1.2x speedup - + FlashAttention-3: Additional attention speedup- Total potential: 2x-3x faster inference**Hardware Requirements:**- FP8 quantization requires CUDA compute capability ≥ 9.0 (H200 ✅)- FlashAttention-3 works on H200 hardware via kernels library- Dynamic shapes add flexibility for variable input sizes## MCP Server Integration
When the user requests an MCP-enabled Gradio app or asks for tool calling capabilities, you MUST enable MCP server functionality.
**🚨 CRITICAL: Enabling MCP Server**To make your Gradio app function as an MCP (Model Control Protocol) server:1. Set `mcp_server=True` in the `.launch()` method2. Add `"gradio[mcp]"` to requirements.txt (not just `gradio`)3. Ensure all functions have detailed docstrings with proper Args sections4. Use type hints for all function parameters
**Example:**```import gradio as gr
def letter_counter(word: str, letter: str) -> int: \"\"\" Count the number of occurrences of a letter in a word or text.
Args: word (str): The input text to search through letter (str): The letter to search for
Returns: int: The number of times the letter appears \"\"\" return word.lower().count(letter.lower())
demo = gr.Interface( fn=letter_counter, inputs=[gr.Textbox("strawberry"), gr.Textbox("r")], outputs=[gr.Number()], title="Letter Counter", description="Count letter occurrences in text.")
if __name__ == "__main__": demo.launch(mcp_server=True)```
**When to Enable MCP:**- User explicitly requests "MCP server" or "MCP-enabled app"- User wants tool calling capabilities for LLMs- User mentions Claude Desktop, Cursor, or Cline integration- User wants to expose functions as tools for AI assistants
**MCP Requirements:**1. **Dependencies:** Always use `gradio[mcp]` in requirements.txt (not plain `gradio`)2. **Docstrings:** Every function must have a detailed docstring with: - Brief description on first line - Args section listing each parameter with type and description - Returns section (optional but recommended)3. **Type Hints:** All parameters must have type hints (e.g., `word: str`, `count: int`)4. **Default Values:** Use default values in components to provide examples
**Best Practices for MCP Tools:**- Use descriptive function names (they become tool names)- Keep functions focused and single-purpose- Accept string parameters when possible for better compatibility- Return simple types (str, int, float, list, dict) rather than complex objects- Use gr.Header for authentication headers when needed- Use gr.Progress() for long-running operations
**Multiple Tools Example:**```import gradio as gr
def add_numbers(a: str, b: str) -> str: \"\"\" Add two numbers together. Args: a (str): First number b (str): Second number Returns: str: Sum of the two numbers \"\"\" return str(int(a) + int(b))
def multiply_numbers(a: str, b: str) -> str: \"\"\" Multiply two numbers. Args: a (str): First number b (str): Second number Returns: str: Product of the two numbers \"\"\" return str(int(a) * int(b))
with gr.Blocks() as demo: gr.Markdown("# Math Tools MCP Server") with gr.Tab("Add"): gr.Interface(add_numbers, [gr.Textbox("5"), gr.Textbox("3")], gr.Textbox()) with gr.Tab("Multiply"): gr.Interface(multiply_numbers, [gr.Textbox("4"), gr.Textbox("7")], gr.Textbox())
if __name__ == "__main__": demo.launch(mcp_server=True)```
**REMEMBER:** If MCP is requested, ALWAYS:1. Set `mcp_server=True` in `.launch()`2. Use `gradio[mcp]` in requirements.txt3. Include complete docstrings with Args sections4. Add type hints to all parameters
## Complete Gradio API Reference
This reference is automatically synced from https://www.gradio.app/llms.txt to ensure accuracy.
""" # Search-enabled prompt search_prompt = """You are an expert Gradio developer with access to real-time web search. Create a complete, working Gradio application based on the user's request. When needed, use web search to find current best practices or verify latest Gradio features. Generate all necessary code to make the application functional and runnable.
## Multi-File Application Structure
When creating complex Gradio applications, organize your code into multiple files for better maintainability:
**File Organization:**- `app.py` - Main application entry point with Gradio interface- `utils.py` - Utility functions and helpers- `models.py` - Model loading and inference functions- `config.py` - Configuration and constants- `requirements.txt` - Python dependencies- Additional modules as needed (e.g., `data_processing.py`, `ui_components.py`)
**🚨 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 process- Only generate the code files listed above
**Output Format for Multi-File Apps:**When generating multi-file applications, use this exact format:
```=== app.py ===[main application code]
=== utils.py ===[utility functions]
=== requirements.txt ===[dependencies]```
**🚨 CRITICAL: requirements.txt Formatting Rules**- Output ONLY plain text package names, one per line- Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)- Do NOT add explanatory text or descriptions- Do NOT wrap in code blocks- Just raw package names as they would appear in a real requirements.txt file- Example of CORRECT format: gradio torch transformers- Example of INCORRECT format (DO NOT DO THIS): ``` gradio # For web interface **Core dependencies:** - torch ```
**Single vs Multi-File Decision:**- Use single file for simple applications (< 100 lines) - but still generate requirements.txt if dependencies exist- Use multi-file structure for complex applications with: - Multiple models or processing pipelines - Extensive utility functions - Complex UI with many components - Data processing workflows - When user specifically requests modular structure
🚨 IMPORTANT: If the user is asking to use external APIs (like OpenRouter, OpenAI API, Hugging Face Inference API, etc.), DO NOT use @spaces.GPU decorators or any ZeroGPU features. External APIs handle the model inference remotely, so GPU allocation on the Spaces instance is not needed.
🚨 CRITICAL REQUIREMENT: If the user provides ANY diffusion model code (FLUX, Stable Diffusion, etc.) that runs locally (not via API), you MUST implement ZeroGPU ahead-of-time (AoT) compilation. This is mandatory and provides 1.3x-1.8x performance improvements. Do not create basic Gradio apps without AoT optimization for diffusion models.
## ZeroGPU Integration (MANDATORY)
ALWAYS use ZeroGPU for GPU-dependent functions in Gradio apps:
1. Import the spaces module: `import spaces`2. Decorate GPU-dependent functions with `@spaces.GPU`3. Specify appropriate duration based on expected runtime: - Quick inference (< 30s): `@spaces.GPU(duration=30)` - Standard generation (30-60s): `@spaces.GPU` (default 60s) - Complex generation (60-120s): `@spaces.GPU(duration=120)` - Heavy processing (120-180s): `@spaces.GPU(duration=180)`
Example usage:```import spacesfrom diffusers import DiffusionPipeline
pipe = DiffusionPipeline.from_pretrained(...)pipe.to('cuda')
@spaces.GPU(duration=120)def generate(prompt): return pipe(prompt).images
gr.Interface( fn=generate, inputs=gr.Text(), outputs=gr.Gallery(),).launch()```
Duration Guidelines:- Shorter durations improve queue priority for users- Text-to-image: typically 30-60 seconds- Image-to-image: typically 20-40 seconds - Video generation: typically 60-180 seconds- Audio/music generation: typically 30-90 seconds- Model loading + inference: add 10-30s buffer- AoT compilation during startup: use @spaces.GPU(duration=1500) for maximum allowed duration
Functions that typically need @spaces.GPU:- Image generation (text-to-image, image-to-image)- Video generation- Audio/music generation- Model inference with transformers, diffusers- Any function using .to('cuda') or GPU operations
## CRITICAL: Use ZeroGPU AoT Compilation for ALL Diffusion Models
FOR ANY DIFFUSION MODEL (FLUX, Stable Diffusion, etc.), YOU MUST IMPLEMENT AHEAD-OF-TIME COMPILATION.This is NOT optional - it provides 1.3x-1.8x speedup and is essential for production ZeroGPU Spaces.
ALWAYS implement this pattern for diffusion models:
### MANDATORY: Basic AoT Compilation PatternYOU MUST USE THIS EXACT PATTERN for any diffusion model (FLUX, Stable Diffusion, etc.):
1. ALWAYS add AoT compilation function with @spaces.GPU(duration=1500)2. ALWAYS use spaces.aoti_capture to capture inputs3. ALWAYS use torch.export.export to export the transformer4. ALWAYS use spaces.aoti_compile to compile5. ALWAYS use spaces.aoti_apply to apply to pipeline
### Required AoT Implementation
For production Spaces with heavy models, use ahead-of-time (AoT) compilation for 1.3x-1.8x speedups:
### Basic AoT Compilation```import spacesimport torchfrom diffusers import DiffusionPipeline
MODEL_ID = 'black-forest-labs/FLUX.1-dev'pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)pipe.to('cuda')
@spaces.GPU(duration=1500) # Maximum duration allowed during startupdef compile_transformer(): # 1. Capture example inputs with spaces.aoti_capture(pipe.transformer) as call: pipe("arbitrary example prompt") # 2. Export the model exported = torch.export.export( pipe.transformer, args=call.args, kwargs=call.kwargs, ) # 3. Compile the exported model return spaces.aoti_compile(exported)
# 4. Apply compiled model to pipelinecompiled_transformer = compile_transformer()spaces.aoti_apply(compiled_transformer, pipe.transformer)
@spaces.GPUdef generate(prompt): return pipe(prompt).images```
### Advanced Optimizations
#### FP8 Quantization (Additional 1.2x speedup on H200)```from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
@spaces.GPU(duration=1500)def compile_transformer_with_quantization(): # Quantize before export for FP8 speedup quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig()) with spaces.aoti_capture(pipe.transformer) as call: pipe("arbitrary example prompt") exported = torch.export.export( pipe.transformer, args=call.args, kwargs=call.kwargs, ) return spaces.aoti_compile(exported)```
#### Dynamic Shapes (Variable input sizes)```from torch.utils._pytree import tree_map
@spaces.GPU(duration=1500)def compile_transformer_dynamic(): with spaces.aoti_capture(pipe.transformer) as call: pipe("arbitrary example prompt") # Define dynamic dimension ranges (model-dependent) transformer_hidden_dim = torch.export.Dim('hidden', min=4096, max=8212) # Map argument names to dynamic dimensions transformer_dynamic_shapes = { "hidden_states": {1: transformer_hidden_dim}, "img_ids": {0: transformer_hidden_dim}, } # Create dynamic shapes structure dynamic_shapes = tree_map(lambda v: None, call.kwargs) dynamic_shapes.update(transformer_dynamic_shapes) exported = torch.export.export( pipe.transformer, args=call.args, kwargs=call.kwargs, dynamic_shapes=dynamic_shapes, ) return spaces.aoti_compile(exported)```
#### Multi-Compile for Different Resolutions```@spaces.GPU(duration=1500)def compile_multiple_resolutions(): compiled_models = {} resolutions = [(512, 512), (768, 768), (1024, 1024)] for width, height in resolutions: # Capture inputs for specific resolution with spaces.aoti_capture(pipe.transformer) as call: pipe(f"test prompt {width}x{height}", width=width, height=height) exported = torch.export.export( pipe.transformer, args=call.args, kwargs=call.kwargs, ) compiled_models[f"{width}x{height}"] = spaces.aoti_compile(exported) return compiled_models
# Usage with resolution dispatchcompiled_models = compile_multiple_resolutions()
@spaces.GPUdef generate_with_resolution(prompt, width=1024, height=1024): resolution_key = f"{width}x{height}" if resolution_key in compiled_models: # Temporarily apply the right compiled model spaces.aoti_apply(compiled_models[resolution_key], pipe.transformer) return pipe(prompt, width=width, height=height).images```
#### FlashAttention-3 Integration```from kernels import get_kernel
# Load pre-built FA3 kernel compatible with H200try: vllm_flash_attn3 = get_kernel("kernels-community/vllm-flash-attn3") print("✅ FlashAttention-3 kernel loaded successfully")except Exception as e: print(f"⚠️ FlashAttention-3 not available: {e}")
# Custom attention processor exampleclass FlashAttention3Processor: def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None): # Use FA3 kernel for attention computation return vllm_flash_attn3(hidden_states, encoder_hidden_states, attention_mask)
# Apply FA3 processor to modelif 'vllm_flash_attn3' in locals(): for name, module in pipe.transformer.named_modules(): if hasattr(module, 'processor'): module.processor = FlashAttention3Processor()```
### Complete Optimized Example```import spacesimport torchfrom diffusers import DiffusionPipelinefrom torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
MODEL_ID = 'black-forest-labs/FLUX.1-dev'pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)pipe.to('cuda')
@spaces.GPU(duration=1500)def compile_optimized_transformer(): # Apply FP8 quantization quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig()) # Capture inputs with spaces.aoti_capture(pipe.transformer) as call: pipe("optimization test prompt") # Export and compile exported = torch.export.export( pipe.transformer, args=call.args, kwargs=call.kwargs, ) return spaces.aoti_compile(exported)
# Compile during startupcompiled_transformer = compile_optimized_transformer()spaces.aoti_apply(compiled_transformer, pipe.transformer)
@spaces.GPUdef generate(prompt): return pipe(prompt).images```
**Expected Performance Gains:**- Basic AoT: 1.3x-1.8x speedup- + FP8 Quantization: Additional 1.2x speedup - + FlashAttention-3: Additional attention speedup- Total potential: 2x-3x faster inference
**Hardware Requirements:**- FP8 quantization requires CUDA compute capability ≥ 9.0 (H200 ✅)- FlashAttention-3 works on H200 hardware via kernels library- Dynamic shapes add flexibility for variable input sizes
## MCP Server Integration
When the user requests an MCP-enabled Gradio app or asks for tool calling capabilities, you MUST enable MCP server functionality.
**🚨 CRITICAL: Enabling MCP Server**To make your Gradio app function as an MCP (Model Control Protocol) server:1. Set `mcp_server=True` in the `.launch()` method2. Add `"gradio[mcp]"` to requirements.txt (not just `gradio`)3. Ensure all functions have detailed docstrings with proper Args sections4. Use type hints for all function parameters
**Example:**```import gradio as gr
def letter_counter(word: str, letter: str) -> int: \"\"\" Count the number of occurrences of a letter in a word or text.
Args: word (str): The input text to search through letter (str): The letter to search for
Returns: int: The number of times the letter appears \"\"\" return word.lower().count(letter.lower())
demo = gr.Interface( fn=letter_counter, inputs=[gr.Textbox("strawberry"), gr.Textbox("r")], outputs=[gr.Number()], title="Letter Counter", description="Count letter occurrences in text.")
if __name__ == "__main__": demo.launch(mcp_server=True)```
**When to Enable MCP:**- User explicitly requests "MCP server" or "MCP-enabled app"- User wants tool calling capabilities for LLMs- User mentions Claude Desktop, Cursor, or Cline integration- User wants to expose functions as tools for AI assistants
**MCP Requirements:**1. **Dependencies:** Always use `gradio[mcp]` in requirements.txt (not plain `gradio`)2. **Docstrings:** Every function must have a detailed docstring with: - Brief description on first line - Args section listing each parameter with type and description - Returns section (optional but recommended)3. **Type Hints:** All parameters must have type hints (e.g., `word: str`, `count: int`)4. **Default Values:** Use default values in components to provide examples
**Best Practices for MCP Tools:**- Use descriptive function names (they become tool names)- Keep functions focused and single-purpose- Accept string parameters when possible for better compatibility- Return simple types (str, int, float, list, dict) rather than complex objects- Use gr.Header for authentication headers when needed- Use gr.Progress() for long-running operations
**Multiple Tools Example:**```import gradio as gr
def add_numbers(a: str, b: str) -> str: \"\"\" Add two numbers together. Args: a (str): First number b (str): Second number Returns: str: Sum of the two numbers \"\"\" return str(int(a) + int(b))
def multiply_numbers(a: str, b: str) -> str: \"\"\" Multiply two numbers. Args: a (str): First number b (str): Second number Returns: str: Product of the two numbers \"\"\" return str(int(a) * int(b))
with gr.Blocks() as demo: gr.Markdown("# Math Tools MCP Server") with gr.Tab("Add"): gr.Interface(add_numbers, [gr.Textbox("5"), gr.Textbox("3")], gr.Textbox()) with gr.Tab("Multiply"): gr.Interface(multiply_numbers, [gr.Textbox("4"), gr.Textbox("7")], gr.Textbox())
if __name__ == "__main__": demo.launch(mcp_server=True)```
**REMEMBER:** If MCP is requested, ALWAYS:1. Set `mcp_server=True` in `.launch()`2. Use `gradio[mcp]` in requirements.txt3. Include complete docstrings with Args sections4. Add type hints to all parameters
## Complete Gradio API Reference
This reference is automatically synced from https://www.gradio.app/llms.txt to ensure accuracy.
""" # Add FastRTC documentation if available if fastrtc_content.strip(): fastrtc_section = f"""## FastRTC Reference Documentation
When building real-time audio/video applications with Gradio, use this FastRTC reference:
{fastrtc_content}
This reference is automatically synced from https://fastrtc.org/llms.txt to ensure accuracy.
""" base_prompt += fastrtc_section search_prompt += fastrtc_section # Update the prompts in the prompts module final_instructions = """\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.
🔍 BEFORE GENERATING: Review the conversation history carefully. If the user has imported any model code (InferenceClient, transformers, diffusers), you MUST integrate that code into your Gradio application. Do not generate standalone inference code - create a complete Gradio app that wraps the imported model functionality.
IMPORTANT: 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""" prompts.GRADIO_SYSTEM_PROMPT = base_prompt + docs_content + final_instructions prompts.GRADIO_SYSTEM_PROMPT_WITH_SEARCH = search_prompt + docs_content + final_instructions
def update_json_system_prompts(): """Update the global JSON system prompts with latest ComfyUI documentation""" docs_content = get_comfyui_docs_content() # Base system prompt for regular JSON base_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 prompt for regular JSON 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.
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 available if docs_content.strip(): comfyui_section = f"""## ComfyUI Reference Documentation
When 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_section search_prompt += comfyui_section # Update the prompts in the prompts module prompts.JSON_SYSTEM_PROMPT = base_prompt prompts.JSON_SYSTEM_PROMPT_WITH_SEARCH = search_prompt
def get_comfyui_system_prompt(): """Get ComfyUI-specific system prompt with enhanced guidance""" docs_content = get_comfyui_docs_content() base_prompt = """You are an expert ComfyUI developer. Generate clean, valid JSON workflows for ComfyUI based on the user's request.
ComfyUI workflows are JSON structures that define:- Nodes: Individual processing units with specific functions- Connections: Links between nodes that define data flow- Parameters: Configuration values for each node- Inputs/Outputs: Data flow between nodes
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 ComfyUI workflow JSON - no HTML, no applications, no explanations outside the JSON. The output should be a complete, valid ComfyUI workflow that can be loaded directly into ComfyUI.
""" # Add ComfyUI documentation if available if docs_content.strip(): comfyui_section = f"""## ComfyUI Reference Documentation
Use this reference for accurate node types, parameters, and workflow structures:
{docs_content}
This reference is automatically synced from https://docs.comfy.org/llms.txt to ensure accuracy.
""" base_prompt += comfyui_section base_prompt += """IMPORTANT: Always include "Built with anycoder" as a comment or metadata field in your ComfyUI workflow JSON that references https://huggingface.co/spaces/akhaliq/anycoder""" return base_prompt
# Initialize Gradio documentation on startupdef initialize_gradio_docs(): """Initialize Gradio documentation on application startup""" try: update_gradio_system_prompts() if should_update_gradio_docs(): print("🚀 Gradio documentation system initialized (fetched fresh content)") else: print("🚀 Gradio documentation system initialized (using cached content)") except 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}")
# Initialize FastRTC documentation on startupdef initialize_fastrtc_docs(): """Initialize FastRTC documentation on application startup""" try: # FastRTC docs are integrated into Gradio system prompts # So we call update_gradio_system_prompts to include FastRTC content update_gradio_system_prompts() if should_update_fastrtc_docs(): print("🚀 FastRTC documentation system initialized (fetched fresh content)") else: print("🚀 FastRTC documentation system initialized (using cached content)") except Exception as e: print(f"Warning: Failed to initialize FastRTC documentation: {e}")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361"""Model inference and client management for AnyCoder.Handles different model providers and inference clients."""import osfrom typing import Dict, List, Optional, Tupleimport refrom http import HTTPStatus
from huggingface_hub import InferenceClientfrom openai import OpenAIfrom mistralai import Mistralimport dashscopefrom google import genaifrom google.genai import types
from .config import HF_TOKEN, AVAILABLE_MODELS
# Type definitionsHistory = List[Dict[str, str]]Messages = List[Dict[str, str]]
def get_inference_client(model_id, provider="auto"): """Return an InferenceClient with provider based on model_id and user selection.""" if model_id == "gemini-3.0-pro": # Use Poe (OpenAI-compatible) client for Gemini 3.0 Pro return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "qwen3-30b-a3b-instruct-2507": # Use DashScope OpenAI client return OpenAI( api_key=os.getenv("DASHSCOPE_API_KEY"), base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", ) elif model_id == "qwen3-30b-a3b-thinking-2507": # Use DashScope OpenAI client for Thinking model return OpenAI( api_key=os.getenv("DASHSCOPE_API_KEY"), base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", ) elif model_id == "qwen3-coder-30b-a3b-instruct": # Use DashScope OpenAI client for Coder model return OpenAI( api_key=os.getenv("DASHSCOPE_API_KEY"), base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", ) elif model_id == "gpt-5": # Use Poe (OpenAI-compatible) client for GPT-5 model return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "gpt-5.1": # Use Poe (OpenAI-compatible) client for GPT-5.1 model return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "gpt-5.1-instant": # Use Poe (OpenAI-compatible) client for GPT-5.1 Instant model return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "gpt-5.1-codex": # Use Poe (OpenAI-compatible) client for GPT-5.1 Codex model return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "gpt-5.1-codex-mini": # Use Poe (OpenAI-compatible) client for GPT-5.1 Codex Mini model return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "grok-4": # Use Poe (OpenAI-compatible) client for Grok-4 model return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "Grok-Code-Fast-1": # Use Poe (OpenAI-compatible) client for Grok-Code-Fast-1 model return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "claude-opus-4.1": # Use Poe (OpenAI-compatible) client for Claude-Opus-4.1 return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "claude-sonnet-4.5": # Use Poe (OpenAI-compatible) client for Claude-Sonnet-4.5 return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "claude-haiku-4.5": # Use Poe (OpenAI-compatible) client for Claude-Haiku-4.5 return OpenAI( api_key=os.getenv("POE_API_KEY"), base_url="https://api.poe.com/v1" ) elif model_id == "qwen3-max-preview": # Use DashScope International OpenAI client for Qwen3 Max Preview return OpenAI( api_key=os.getenv("DASHSCOPE_API_KEY"), base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", ) elif model_id == "openrouter/sonoma-dusk-alpha": # Use OpenRouter client for Sonoma Dusk Alpha model return OpenAI( api_key=os.getenv("OPENROUTER_API_KEY"), base_url="https://openrouter.ai/api/v1", ) elif model_id == "openrouter/sonoma-sky-alpha": # Use OpenRouter client for Sonoma Sky Alpha model return OpenAI( api_key=os.getenv("OPENROUTER_API_KEY"), base_url="https://openrouter.ai/api/v1", ) elif model_id == "x-ai/grok-4.1-fast": # Use OpenRouter client for Grok 4.1 Fast model return OpenAI( api_key=os.getenv("OPENROUTER_API_KEY"), base_url="https://openrouter.ai/api/v1", ) elif model_id == "openrouter/sherlock-think-alpha": # Use OpenRouter client for Sherlock Think Alpha model return OpenAI( api_key=os.getenv("OPENROUTER_API_KEY"), base_url="https://openrouter.ai/api/v1", ) elif model_id == "MiniMaxAI/MiniMax-M2": # Use HuggingFace InferenceClient with Novita provider for MiniMax M2 model provider = "novita" elif model_id == "step-3": # Use StepFun API client for Step-3 model return OpenAI( api_key=os.getenv("STEP_API_KEY"), base_url="https://api.stepfun.com/v1" ) elif model_id == "codestral-2508" or model_id == "mistral-medium-2508": # Use Mistral client for Mistral models return Mistral(api_key=os.getenv("MISTRAL_API_KEY")) elif model_id == "gemini-2.5-flash": # Use Google Gemini (OpenAI-compatible) client return OpenAI( api_key=os.getenv("GEMINI_API_KEY"), base_url="https://generativelanguage.googleapis.com/v1beta/openai/", ) elif model_id == "gemini-2.5-pro": # Use Google Gemini Pro (OpenAI-compatible) client return OpenAI( api_key=os.getenv("GEMINI_API_KEY"), base_url="https://generativelanguage.googleapis.com/v1beta/openai/", ) elif model_id == "gemini-flash-latest": # Use Google Gemini Flash Latest (OpenAI-compatible) client return OpenAI( api_key=os.getenv("GEMINI_API_KEY"), base_url="https://generativelanguage.googleapis.com/v1beta/openai/", ) elif model_id == "gemini-flash-lite-latest": # Use Google Gemini Flash Lite Latest (OpenAI-compatible) client return OpenAI( api_key=os.getenv("GEMINI_API_KEY"), base_url="https://generativelanguage.googleapis.com/v1beta/openai/", ) elif model_id == "kimi-k2-turbo-preview": # Use Moonshot AI (OpenAI-compatible) client for Kimi K2 Turbo (Preview) return OpenAI( api_key=os.getenv("MOONSHOT_API_KEY"), base_url="https://api.moonshot.ai/v1", ) elif model_id == "moonshotai/Kimi-K2-Thinking": # Use HuggingFace InferenceClient with Together AI provider for Kimi K2 Thinking provider = "together" elif model_id == "stealth-model-1": # Use stealth model with generic configuration api_key = os.getenv("STEALTH_MODEL_1_API_KEY") if not api_key: raise ValueError("STEALTH_MODEL_1_API_KEY environment variable is required for Carrot model") base_url = os.getenv("STEALTH_MODEL_1_BASE_URL") if not base_url: raise ValueError("STEALTH_MODEL_1_BASE_URL environment variable is required for Carrot model") return OpenAI( api_key=api_key, base_url=base_url, ) elif model_id == "moonshotai/Kimi-K2-Instruct": provider = "groq" elif model_id == "deepseek-ai/DeepSeek-V3.1": provider = "novita" elif model_id == "deepseek-ai/DeepSeek-V3.1-Terminus": provider = "novita" elif model_id == "deepseek-ai/DeepSeek-V3.2-Exp": provider = "novita" elif model_id == "zai-org/GLM-4.5": provider = "fireworks-ai" elif model_id == "zai-org/GLM-4.6": # Use Cerebras provider for GLM-4.6 via HuggingFace provider = "cerebras" return InferenceClient( provider=provider, api_key=HF_TOKEN, bill_to="huggingface" )
# Helper function to get real model ID for stealth models and special casesdef get_real_model_id(model_id: str) -> str: """Get the real model ID, checking environment variables for stealth models and handling special model formats""" if model_id == "stealth-model-1": # Get the real model ID from environment variable real_model_id = os.getenv("STEALTH_MODEL_1_ID") if not real_model_id: raise ValueError("STEALTH_MODEL_1_ID environment variable is required for Carrot model") return real_model_id elif model_id == "zai-org/GLM-4.6": # GLM-4.6 requires Cerebras provider suffix in model string for API calls return "zai-org/GLM-4.6:cerebras" elif model_id == "moonshotai/Kimi-K2-Thinking": # Kimi K2 Thinking needs Together AI provider return "moonshotai/Kimi-K2-Thinking:together" return model_id
# Type definitionsHistory = List[Tuple[str, str]]Messages = List[Dict[str, str]]
def history_to_messages(history: History, system: str) -> Messages: messages = [{'role': 'system', 'content': system}] for h in history: # Handle multimodal content in history user_content = h[0] if isinstance(user_content, list): # Extract text from multimodal content text_content = "" for item in user_content: if isinstance(item, dict) and item.get("type") == "text": text_content += item.get("text", "") user_content = text_content if text_content else str(user_content) messages.append({'role': 'user', 'content': user_content}) messages.append({'role': 'assistant', 'content': h[1]}) return messages
def history_to_chatbot_messages(history: History) -> List[Dict[str, str]]: """Convert history tuples to chatbot message format""" messages = [] for user_msg, assistant_msg in history: # Handle multimodal content if isinstance(user_msg, list): text_content = "" for item in user_msg: if isinstance(item, dict) and item.get("type") == "text": text_content += item.get("text", "") user_msg = text_content if text_content else str(user_msg) messages.append({"role": "user", "content": user_msg}) messages.append({"role": "assistant", "content": assistant_msg}) return messages
def strip_tool_call_markers(text): """Remove TOOL_CALL markers that some LLMs (like Qwen) add to their output.""" if not text: return text # Remove [TOOL_CALL] and [/TOOL_CALL] markers text = re.sub(r'\[/?TOOL_CALL\]', '', text, flags=re.IGNORECASE) # Remove standalone }} that appears with tool calls # Only remove if it's on its own line or at the end text = re.sub(r'^\s*\}\}\s*$', '', text, flags=re.MULTILINE) return text.strip()
def remove_code_block(text): # First strip any tool call markers text = strip_tool_call_markers(text) # Try to match code blocks with language markers patterns = [ r'```(?:html|HTML)\n([\s\S]+?)\n```', # Match ```html or ```HTML r'```\n([\s\S]+?)\n```', # Match code blocks without language markers r'```([\s\S]+?)```' # Match code blocks without line breaks ] for pattern in patterns: match = re.search(pattern, text, re.DOTALL) if match: extracted = match.group(1).strip() # Remove a leading language marker line (e.g., 'python') if present if extracted.split('\n', 1)[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']: return extracted.split('\n', 1)[1] if '\n' in extracted else '' # If HTML markup starts later in the block (e.g., Poe injected preface), trim to first HTML root html_root_idx = None for tag in ['<!DOCTYPE html', '<html']: idx = extracted.find(tag) if idx != -1: html_root_idx = idx if html_root_idx is None else min(html_root_idx, idx) if html_root_idx is not None and html_root_idx > 0: return extracted[html_root_idx:].strip() return extracted # If no code block is found, check if the entire text is HTML stripped = text.strip() if stripped.startswith('<!DOCTYPE html>') or stripped.startswith('<html') or stripped.startswith('<'): # If HTML root appears later (e.g., Poe preface), trim to first HTML root for tag in ['<!DOCTYPE html', '<html']: idx = stripped.find(tag) if idx > 0: return stripped[idx:].strip() return stripped # Special handling for python: remove python marker if text.strip().startswith('```python'): return text.strip()[9:-3].strip() # Remove a leading language marker line if present (fallback) lines = text.strip().split('\n', 1) if lines[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']: return lines[1] if len(lines) > 1 else '' return text.strip()
## React CDN compatibility fixer removed per user preference
def strip_thinking_tags(text: str) -> str: """Strip <think> tags and [TOOL_CALL] markers from streaming output.""" if not text: return text # Remove <think> opening tags text = re.sub(r'<think>', '', text, flags=re.IGNORECASE) # Remove </think> closing tags text = re.sub(r'</think>', '', text, flags=re.IGNORECASE) # Remove [TOOL_CALL] markers text = re.sub(r'\[/?TOOL_CALL\]', '', text, flags=re.IGNORECASE) return text
def strip_placeholder_thinking(text: str) -> str: """Remove placeholder 'Thinking...' status lines from streamed text.""" if not text: return text # Matches lines like: "Thinking..." or "Thinking... (12s elapsed)" return re.sub(r"(?mi)^[\t ]*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?[\t ]*$\n?", "", text)
def is_placeholder_thinking_only(text: str) -> bool: """Return True if text contains only 'Thinking...' placeholder lines (with optional elapsed).""" if not text: return False stripped = text.strip() if not stripped: return False return re.fullmatch(r"(?s)(?:\s*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?\s*)+", stripped) is not None
def extract_last_thinking_line(text: str) -> str: """Extract the last 'Thinking...' line to display as status.""" matches = list(re.finditer(r"Thinking\.\.\.(?:\s*\(\d+s elapsed\))?", text)) return matches[-1].group(0) if matches else "Thinking..."
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111"""Code parsing and formatting utilities for different frameworks.Handles parsing of transformers.js, React, multi-file HTML, Streamlit, and Gradio code."""import reimport osimport jsonimport base64from typing import Dict, List, Optional, Tuplefrom bs4 import BeautifulSoupimport html
from .config import SEARCH_START, DIVIDER, REPLACE_END
# Type definitionsHistory = List[Dict[str, str]]
def strip_tool_call_markers(text): """Remove TOOL_CALL markers and thinking tags that some LLMs add to their output.""" if not text: return text # Remove [TOOL_CALL] and [/TOOL_CALL] markers text = re.sub(r'\[/?TOOL_CALL\]', '', text, flags=re.IGNORECASE) # Remove <think> and </think> tags and their content text = re.sub(r'<think>[\s\S]*?</think>', '', text, flags=re.IGNORECASE) # Remove any remaining unclosed <think> tags at the start text = re.sub(r'^<think>[\s\S]*?(?=\n|$)', '', text, flags=re.IGNORECASE | re.MULTILINE) # Remove any remaining </think> tags text = re.sub(r'</think>', '', text, flags=re.IGNORECASE) # Remove standalone }} that appears with tool calls # Only remove if it's on its own line or at the end text = re.sub(r'^\s*\}\}\s*$', '', text, flags=re.MULTILINE) return text.strip()
def remove_code_block(text): # First strip any tool call markers text = strip_tool_call_markers(text) # Try to match code blocks with language markers patterns = [ r'```(?:html|HTML)\n([\s\S]+?)\n```', # Match ```html or ```HTML r'```\n([\s\S]+?)\n```', # Match code blocks without language markers r'```([\s\S]+?)```' # Match code blocks without line breaks ] for pattern in patterns: match = re.search(pattern, text, re.DOTALL) if match: extracted = match.group(1).strip() # Remove a leading language marker line (e.g., 'python') if present if extracted.split('\n', 1)[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']: return extracted.split('\n', 1)[1] if '\n' in extracted else '' # If HTML markup starts later in the block (e.g., Poe injected preface), trim to first HTML root html_root_idx = None for tag in ['<!DOCTYPE html', '<html']: idx = extracted.find(tag) if idx != -1: html_root_idx = idx if html_root_idx is None else min(html_root_idx, idx) if html_root_idx is not None and html_root_idx > 0: return extracted[html_root_idx:].strip() return extracted # If no code block is found, check if the entire text is HTML stripped = text.strip() if stripped.startswith('<!DOCTYPE html>') or stripped.startswith('<html') or stripped.startswith('<'): # If HTML root appears later (e.g., Poe preface), trim to first HTML root for tag in ['<!DOCTYPE html', '<html']: idx = stripped.find(tag) if idx > 0: return stripped[idx:].strip() return stripped # Special handling for python: remove python marker if text.strip().startswith('```python'): return text.strip()[9:-3].strip() # Remove a leading language marker line if present (fallback) lines = text.strip().split('\n', 1) if lines[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']: return lines[1] if len(lines) > 1 else '' return text.strip()
## React CDN compatibility fixer removed per user preference
def strip_placeholder_thinking(text: str) -> str: """Remove placeholder 'Thinking...' status lines from streamed text.""" if not text: return text # Matches lines like: "Thinking..." or "Thinking... (12s elapsed)" return re.sub(r"(?mi)^[\t ]*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?[\t ]*$\n?", "", text)
def is_placeholder_thinking_only(text: str) -> bool: """Return True if text contains only 'Thinking...' placeholder lines (with optional elapsed).""" if not text: return False stripped = text.strip() if not stripped: return False return re.fullmatch(r"(?s)(?:\s*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?\s*)+", stripped) is not None
def extract_last_thinking_line(text: str) -> str: """Extract the last 'Thinking...' line to display as status.""" matches = list(re.finditer(r"Thinking\.\.\.(?:\s*\(\d+s elapsed\))?", text)) return matches[-1].group(0) if matches else "Thinking..."
def parse_transformers_js_output(text): """Parse transformers.js output and extract the three files (index.html, index.js, style.css)""" files = { 'index.html': '', 'index.js': '', 'style.css': '' } # Multiple patterns to match the three code blocks with different variations html_patterns = [ r'```html\s*\n([\s\S]*?)(?:```|\Z)', r'```htm\s*\n([\s\S]*?)(?:```|\Z)', r'```\s*(?:index\.html|html)\s*\n([\s\S]*?)(?:```|\Z)' ] js_patterns = [ r'```javascript\s*\n([\s\S]*?)(?:```|\Z)', r'```js\s*\n([\s\S]*?)(?:```|\Z)', r'```\s*(?:index\.js|javascript|js)\s*\n([\s\S]*?)(?:```|\Z)' ] css_patterns = [ r'```css\s*\n([\s\S]*?)(?:```|\Z)', r'```\s*(?:style\.css|css)\s*\n([\s\S]*?)(?:```|\Z)' ] # Extract HTML content for pattern in html_patterns: html_match = re.search(pattern, text, re.IGNORECASE) if html_match: files['index.html'] = html_match.group(1).strip() break # Extract JavaScript content for pattern in js_patterns: js_match = re.search(pattern, text, re.IGNORECASE) if js_match: files['index.js'] = js_match.group(1).strip() break # Extract CSS content for pattern in css_patterns: css_match = re.search(pattern, text, re.IGNORECASE) if css_match: files['style.css'] = css_match.group(1).strip() break # Fallback: support === index.html === format if any file is missing if not (files['index.html'] and files['index.js'] and files['style.css']): # Use regex to extract sections html_fallback = re.search(r'===\s*index\.html\s*===\s*\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE) js_fallback = re.search(r'===\s*index\.js\s*===\s*\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE) css_fallback = re.search(r'===\s*style\.css\s*===\s*\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE) if html_fallback: files['index.html'] = html_fallback.group(1).strip() if js_fallback: files['index.js'] = js_fallback.group(1).strip() if css_fallback: files['style.css'] = css_fallback.group(1).strip() # Additional fallback: extract from numbered sections or file headers if not (files['index.html'] and files['index.js'] and files['style.css']): # Try patterns like "1. index.html:" or "**index.html**" patterns = [ (r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)index\.html(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'index.html'), (r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)index\.js(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'index.js'), (r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)style\.css(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'style.css') ] for pattern, file_key in patterns: if not files[file_key]: match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE) if match: # Clean up the content by removing any code block markers content = match.group(1).strip() content = re.sub(r'^```\w*\s*\n', '', content) content = re.sub(r'\n```\s*$', '', content) files[file_key] = content.strip() return files
def format_transformers_js_output(files): """Format the three files into a single display string""" output = [] output.append("=== index.html ===") output.append(files['index.html']) output.append("\n=== index.js ===") output.append(files['index.js']) output.append("\n=== style.css ===") output.append(files['style.css']) return '\n'.join(output)
def build_transformers_inline_html(files: dict) -> str: """Merge transformers.js three-file output into a single self-contained HTML document.
- Inlines style.css into a <style> tag - Inlines index.js into a <script type="module"> tag - Rewrites ESM imports for transformers.js to a stable CDN URL so it works in data: iframes """ import re as _re
html = files.get('index.html') or '' js = files.get('index.js') or '' css = files.get('style.css') or ''
# Normalize JS imports to CDN (handle both @huggingface/transformers and legacy @xenova/transformers) cdn_url = "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.3"
def _normalize_imports(_code: str) -> str: if not _code: return _code or "" _code = _re.sub(r"from\s+['\"]@huggingface/transformers['\"]", f"from '{cdn_url}'", _code) _code = _re.sub(r"from\s+['\"]@xenova/transformers['\"]", f"from '{cdn_url}'", _code) _code = _re.sub(r"from\s+['\"]https://cdn.jsdelivr.net/npm/@huggingface/transformers@[^'\"]+['\"]", f"from '{cdn_url}'", _code) _code = _re.sub(r"from\s+['\"]https://cdn.jsdelivr.net/npm/@xenova/transformers@[^'\"]+['\"]", f"from '{cdn_url}'", _code) return _code
# Extract inline module scripts from index.html, then merge into JS so we control imports inline_modules = [] try: for _m in _re.finditer(r"<script\\b[^>]*type=[\"\']module[\"\'][^>]*>([\s\S]*?)</script>", html, flags=_re.IGNORECASE): inline_modules.append(_m.group(1)) if inline_modules: html = _re.sub(r"<script\\b[^>]*type=[\"\']module[\"\'][^>]*>[\s\S]*?</script>\\s*", "", html, flags=_re.IGNORECASE) # Normalize any external module script URLs that load transformers to a single CDN version (keep the tag) html = _re.sub(r"https://cdn\.jsdelivr\.net/npm/@huggingface/transformers@[^'\"<>\s]+", cdn_url, html) html = _re.sub(r"https://cdn\.jsdelivr\.net/npm/@xenova/transformers@[^'\"<>\s]+", cdn_url, html) except Exception: # Best-effort; continue pass
# Merge inline module code with provided index.js, then normalize imports combined_js_parts = [] if inline_modules: combined_js_parts.append("\n\n".join(inline_modules)) if js: combined_js_parts.append(js) js = "\n\n".join([p for p in combined_js_parts if (p and p.strip())]) js = _normalize_imports(js)
# Prepend a small prelude to reduce persistent caching during preview # Also ensure a global `transformers` namespace exists for apps relying on it # Note: importing env alongside user's own imports is fine in ESM if js.strip(): prelude = ( f"import {{ env }} from '{cdn_url}';\n" "try { env.useBrowserCache = false; } catch (e) {}\n" "try { if (env && env.backends && env.backends.onnx && env.backends.onnx.wasm) { env.backends.onnx.wasm.numThreads = 1; env.backends.onnx.wasm.proxy = false; } } catch (e) {}\n" f"(async () => {{ try {{ if (typeof globalThis.transformers === 'undefined') {{ const m = await import('{cdn_url}'); globalThis.transformers = m; }} }} catch (e) {{}} }})();\n" ) js = prelude + js
# If index.html missing or doesn't look like a full document, create a minimal shell doc = html.strip() if not doc or ('<html' not in doc.lower()): doc = ( "<!DOCTYPE html>\n" "<html>\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Transformers.js App</title>\n</head>\n" "<body>\n<div id=\"app\"></div>\n</body>\n</html>" )
# Remove local references to style.css and index.js to avoid duplicates when inlining doc = _re.sub(r"<link[^>]+href=\"[^\"]*style\.css\"[^>]*>\s*", "", doc, flags=_re.IGNORECASE) doc = _re.sub(r"<script[^>]+src=\"[^\"]*index\.js\"[^>]*>\s*</script>\s*", "", doc, flags=_re.IGNORECASE)
# Inline CSS: insert before </head> or create a <head> style_tag = f"<style>\n{css}\n</style>" if css else "" if style_tag: if '</head>' in doc.lower(): # Preserve original casing by finding closing head case-insensitively match = _re.search(r"</head>", doc, flags=_re.IGNORECASE) if match: idx = match.start() doc = doc[:idx] + style_tag + doc[idx:] else: # No head; insert at top of body match = _re.search(r"<body[^>]*>", doc, flags=_re.IGNORECASE) if match: idx = match.end() doc = doc[:idx] + "\n" + style_tag + doc[idx:] else: # Append at beginning doc = style_tag + doc
# Inline JS: insert before </body> script_tag = f"<script type=\"module\">\n{js}\n</script>" if js else "" # Lightweight debug console overlay to surface runtime errors inside the iframe debug_overlay = ( "<style>\n" "#anycoder-debug{position:fixed;left:0;right:0;bottom:0;max-height:45%;overflow:auto;" "background:rgba(0,0,0,.85);color:#9eff9e;padding:.5em;font:12px/1.4 monospace;z-index:2147483647;display:none}" "#anycoder-debug pre{margin:0;white-space:pre-wrap;word-break:break-word}" "</style>\n" "<div id=\"anycoder-debug\"></div>\n" "<script>\n" "(function(){\n" " const el = document.getElementById('anycoder-debug');\n" " function show(){ if(el && el.style.display!=='block'){ el.style.display='block'; } }\n" " function log(msg){ try{ show(); const pre=document.createElement('pre'); pre.textContent=msg; el.appendChild(pre);}catch(e){} }\n" " const origError = console.error.bind(console);\n" " console.error = function(){ origError.apply(console, arguments); try{ log('console.error: ' + Array.from(arguments).map(a=>{try{return (typeof a==='string')?a:JSON.stringify(a);}catch(e){return String(a);}}).join(' ')); }catch(e){} };\n" " window.addEventListener('error', e => { log('window.onerror: ' + (e && e.message ? e.message : 'Unknown error')); });\n" " window.addEventListener('unhandledrejection', e => { try{ const r=e && e.reason; log('unhandledrejection: ' + (r && (r.message || JSON.stringify(r)))); }catch(err){ log('unhandledrejection'); } });\n" "})();\n" "</script>" ) # Cleanup script to clear Cache Storage and IndexedDB on unload to free model weights cleanup_tag = ( "<script>\n" "(function(){\n" " function cleanup(){\n" " try { if (window.caches && caches.keys) { caches.keys().then(keys => keys.forEach(k => caches.delete(k))); } } catch(e){}\n" " try { if (window.indexedDB && indexedDB.databases) { indexedDB.databases().then(dbs => dbs.forEach(db => db && db.name && indexedDB.deleteDatabase(db.name))); } } catch(e){}\n" " }\n" " window.addEventListener('pagehide', cleanup, { once: true });\n" " window.addEventListener('beforeunload', cleanup, { once: true });\n" "})();\n" "</script>" ) if script_tag: match = _re.search(r"</body>", doc, flags=_re.IGNORECASE) if match: idx = match.start() doc = doc[:idx] + debug_overlay + script_tag + cleanup_tag + doc[idx:] else: # Append at end doc = doc + debug_overlay + script_tag + cleanup_tag
return doc
def send_transformers_to_sandbox(files: dict) -> str: """Build a self-contained HTML document from transformers.js files and return an iframe preview.""" merged_html = build_transformers_inline_html(files) return send_to_sandbox(merged_html)
def parse_multipage_html_output(text: str) -> Dict[str, str]: """Parse multi-page HTML output formatted as repeated "=== filename ===" sections.
Returns a mapping of filename → file content. Supports nested paths like assets/css/styles.css. If HTML content appears before the first === marker, it's treated as index.html. """ if not text: return {} # First, strip any markdown fences cleaned = remove_code_block(text) files: Dict[str, str] = {} import re as _re # Check if there's content before the first === marker first_marker_match = _re.search(r"^===\s*([^=\n]+?)\s*===", cleaned, _re.MULTILINE) if first_marker_match: # There's content before the first marker first_marker_pos = first_marker_match.start() if first_marker_pos > 0: leading_content = cleaned[:first_marker_pos].strip() # Check if it looks like HTML content if leading_content and ('<!DOCTYPE' in leading_content or '<html' in leading_content or leading_content.startswith('<')): files['index.html'] = leading_content # Now parse the rest with === markers remaining_text = cleaned[first_marker_pos:] if first_marker_pos > 0 else cleaned pattern = _re.compile(r"^===\s*([^=\n]+?)\s*===\s*\n([\s\S]*?)(?=\n===\s*[^=\n]+?\s*===|\Z)", _re.MULTILINE) for m in pattern.finditer(remaining_text): name = m.group(1).strip() content = m.group(2).strip() # Remove accidental trailing fences if present content = _re.sub(r"^```\w*\s*\n|\n```\s*$", "", content) files[name] = content else: # No === markers found, try standard pattern matching pattern = _re.compile(r"^===\s*([^=\n]+?)\s*===\s*\n([\s\S]*?)(?=\n===\s*[^=\n]+?\s*===|\Z)", _re.MULTILINE) for m in pattern.finditer(cleaned): name = m.group(1).strip() content = m.group(2).strip() # Remove accidental trailing fences if present content = _re.sub(r"^```\w*\s*\n|\n```\s*$", "", content) files[name] = content return files
def format_multipage_output(files: Dict[str, str]) -> str: """Format a dict of files back into === filename === sections.
Ensures `index.html` appears first if present; others follow sorted by path. """ if not isinstance(files, dict) or not files: return "" ordered_paths = [] if 'index.html' in files: ordered_paths.append('index.html') for path in sorted(files.keys()): if path == 'index.html': continue ordered_paths.append(path) parts: list[str] = [] for path in ordered_paths: parts.append(f"=== {path} ===") # Avoid trailing extra newlines to keep blocks compact parts.append((files.get(path) or '').rstrip()) return "\n".join(parts)
def validate_and_autofix_files(files: Dict[str, str]) -> Dict[str, str]: """Ensure minimal contract for multi-file sites; auto-fix missing pieces.
Rules: - Ensure at least one HTML entrypoint (index.html). If none, synthesize a simple index.html linking discovered pages. - For each HTML file, ensure referenced local assets exist in files; if missing, add minimal stubs. - Normalize relative paths (strip leading '/'). """ if not isinstance(files, dict) or not files: return files or {} import re as _re
normalized: Dict[str, str] = {} for k, v in files.items(): safe_key = k.strip().lstrip('/') normalized[safe_key] = v
html_files = [p for p in normalized.keys() if p.lower().endswith('.html')] has_index = 'index.html' in normalized
# If no index.html but some HTML pages exist, create a simple hub index linking to them if not has_index and html_files: links = '\n'.join([f"<li><a href=\"{p}\">{p}</a></li>" for p in html_files]) normalized['index.html'] = ( "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n" "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n" "<title>Site Index</title>\n</head>\n<body>\n<h1>Site</h1>\n<ul>\n" + links + "\n</ul>\n</body>\n</html>" )
# Collect references from HTML files asset_refs: set[str] = set() link_href = _re.compile(r"<link[^>]+href=\"([^\"]+)\"") script_src = _re.compile(r"<script[^>]+src=\"([^\"]+)\"") img_src = _re.compile(r"<img[^>]+src=\"([^\"]+)\"") a_href = _re.compile(r"<a[^>]+href=\"([^\"]+)\"")
for path, content in list(normalized.items()): if not path.lower().endswith('.html'): continue for patt in (link_href, script_src, img_src, a_href): for m in patt.finditer(content or ""): ref = (m.group(1) or "").strip() if not ref or ref.startswith('http://') or ref.startswith('https://') or ref.startswith('data:') or '#' in ref: continue asset_refs.add(ref.lstrip('/'))
# Add minimal stubs for missing local references (CSS/JS/pages only, not images) for ref in list(asset_refs): if ref not in normalized: if ref.lower().endswith('.css'): normalized[ref] = "/* generated stub */\n" elif ref.lower().endswith('.js'): normalized[ref] = "// generated stub\n" elif ref.lower().endswith('.html'): normalized[ref] = ( "<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/><title>Page</title></head>\n" "<body><main><h1>Placeholder page</h1><p>This page was auto-created to satisfy an internal link.</p></main></body>\n</html>" ) # Note: We no longer create placeholder image files automatically # This prevents unwanted SVG stub files from being generated during image generation
return normalizeddef inline_multipage_into_single_preview(files: Dict[str, str]) -> str: """Inline local CSS/JS referenced by index.html for preview inside a data: iframe.
- Uses index.html as the base document - Inlines <link href="..."> if the target exists in files - Inlines <script src="..."> if the target exists in files - Leaves other links (e.g., about.html) untouched; preview covers the home page """ import re as _re html = files.get('index.html', '') if not html: return "" doc = html # Inline CSS links that point to known files def _inline_css(match): href = match.group(1) if href in files: return f"<style>\n{files[href]}\n</style>" return match.group(0) doc = _re.sub(r"<link[^>]+href=\"([^\"]+)\"[^>]*/?>", _inline_css, doc, flags=_re.IGNORECASE)
# Inline JS scripts that point to known files def _inline_js(match): src = match.group(1) if src in files: return f"<script>\n{files[src]}\n</script>" return match.group(0) doc = _re.sub(r"<script[^>]+src=\"([^\"]+)\"[^>]*>\s*</script>", _inline_js, doc, flags=_re.IGNORECASE)
# Inject a lightweight in-iframe client-side navigator to load other HTML files try: import json as _json import base64 as _b64 import re as _re html_pages = {k: v for k, v in files.items() if k.lower().endswith('.html')} # Ensure index.html entry restores the current body's HTML _m_body = _re.search(r"<body[^>]*>([\s\S]*?)</body>", doc, flags=_re.IGNORECASE) _index_body = _m_body.group(1) if _m_body else doc html_pages['index.html'] = _index_body encoded = _b64.b64encode(_json.dumps(html_pages).encode('utf-8')).decode('ascii') nav_script = ( "<script>\n" # Simple client-side loader for internal links "(function(){\n" f" const MP_FILES = JSON.parse(atob('{encoded}'));\n" " function extractBody(html){\n" " try {\n" " const doc = new DOMParser().parseFromString(html, 'text/html');\n" " const title = doc.querySelector('title'); if (title) document.title = title.textContent || document.title;\n" " return doc.body ? doc.body.innerHTML : html;\n" " } catch(e){ return html; }\n" " }\n" " function loadPage(path){\n" " if (!MP_FILES[path]) return false;\n" " const bodyHTML = extractBody(MP_FILES[path]);\n" " document.body.innerHTML = bodyHTML;\n" " attach();\n" " try { history.replaceState({}, '', '#'+path); } catch(e){}\n" " return true;\n" " }\n" " function clickHandler(e){\n" " const a = e.target && e.target.closest ? e.target.closest('a') : null;\n" " if (!a) return;\n" " const href = a.getAttribute('href') || '';\n" " if (!href || href.startsWith('#') || /^https?:/i.test(href) || href.startsWith('mailto:') || href.startsWith('tel:')) return;\n" " const clean = href.split('#')[0].split('?')[0];\n" " if (MP_FILES[clean]) { e.preventDefault(); loadPage(clean); }\n" " }\n" " function attach(){ document.removeEventListener('click', clickHandler, true); document.addEventListener('click', clickHandler, true); }\n" " document.addEventListener('DOMContentLoaded', function(){ attach(); const initial = (location.hash||'').slice(1); if (initial && MP_FILES[initial]) loadPage(initial); }, { once:true });\n" "})();\n" "</script>" ) m = _re.search(r"</body>", doc, flags=_re.IGNORECASE) if m: i = m.start() doc = doc[:i] + nav_script + doc[i:] else: doc = doc + nav_script except Exception: # Non-fatal in preview pass
return doc
def extract_html_document(text: str) -> str: """Return substring starting from the first <!DOCTYPE html> or <html> if present, else original text.
This ignores prose or planning notes before the actual HTML so previews don't break. """ if not text: return text lower = text.lower() idx = lower.find("<!doctype html") if idx == -1: idx = lower.find("<html") return text[idx:] if idx != -1 else text
def parse_react_output(text): """Parse React/Next.js output to extract individual files.
Supports multi-file sections using === filename === sections. """ if not text: return {}
# Use the generic multipage parser try: files = parse_multipage_html_output(text) or {} except Exception: files = {}
return files if isinstance(files, dict) and files else {}
def history_render(history: History): return gr.update(visible=True), history
def clear_history(): return [], [], [] # Empty lists for history, history_output, and chat_history
def create_multimodal_message(text, image=None): """Create a chat message. For broad provider compatibility, always return content as a string.
Some providers (e.g., Hugging Face router endpoints like Cerebras) expect `content` to be a string, not a list of typed parts. To avoid 422 validation errors, we inline a brief note when an image is provided. """ if image is None: return {"role": "user", "content": text} # Keep providers happy: avoid structured multimodal payloads; add a short note instead # If needed, this can be enhanced per-model with proper multimodal schemas. return {"role": "user", "content": f"{text}\n\n[An image was provided as reference.]"}def apply_search_replace_changes(original_content: str, changes_text: str) -> str: """Apply search/replace changes to content (HTML, Python, etc.)""" if not changes_text.strip(): return original_content # If the model didn't use the block markers, try a CSS-rule fallback where # provided blocks like `.selector { ... }` replace matching CSS rules. if (SEARCH_START not in changes_text) and (DIVIDER not in changes_text) and (REPLACE_END not in changes_text): try: import re # Local import to avoid global side effects updated_content = original_content replaced_any_rule = False # Find CSS-like rule blocks in the changes_text # This is a conservative matcher that looks for `selector { ... }` css_blocks = re.findall(r"([^{]+)\{([\s\S]*?)\}", changes_text, flags=re.MULTILINE) for selector_raw, body_raw in css_blocks: selector = selector_raw.strip() body = body_raw.strip() if not selector: continue # Build a regex to find the existing rule for this selector # Capture opening `{` and closing `}` to preserve them; replace inner body. pattern = re.compile(rf"({re.escape(selector)}\s*\{{)([\s\S]*?)(\}})") def _replace_rule(match): nonlocal replaced_any_rule replaced_any_rule = True prefix, existing_body, suffix = match.groups() # Preserve indentation of the existing first body line if present first_line_indent = "" for line in existing_body.splitlines(): stripped = line.lstrip(" \t") if stripped: first_line_indent = line[: len(line) - len(stripped)] break # Re-indent provided body with the detected indent if body: new_body_lines = [first_line_indent + line if line.strip() else line for line in body.splitlines()] new_body_text = "\n" + "\n".join(new_body_lines) + "\n" else: new_body_text = existing_body # If empty body provided, keep existing return f"{prefix}{new_body_text}{suffix}" updated_content, num_subs = pattern.subn(_replace_rule, updated_content, count=1) if replaced_any_rule: return updated_content except Exception: # Fallback silently to the standard block-based application pass
# Split the changes text into individual search/replace blocks blocks = [] current_block = "" lines = changes_text.split('\n') for line in lines: if line.strip() == SEARCH_START: if current_block.strip(): blocks.append(current_block.strip()) current_block = line + '\n' elif line.strip() == REPLACE_END: current_block += line + '\n' blocks.append(current_block.strip()) current_block = "" else: current_block += line + '\n' if current_block.strip(): blocks.append(current_block.strip()) modified_content = original_content for block in blocks: if not block.strip(): continue # Parse the search/replace block lines = block.split('\n') search_lines = [] replace_lines = [] in_search = False in_replace = False for line in lines: if line.strip() == SEARCH_START: in_search = True in_replace = False elif line.strip() == DIVIDER: in_search = False in_replace = True elif line.strip() == REPLACE_END: in_replace = False elif in_search: search_lines.append(line) elif in_replace: replace_lines.append(line) # Apply the search/replace if search_lines: search_text = '\n'.join(search_lines).strip() replace_text = '\n'.join(replace_lines).strip() if search_text in modified_content: modified_content = modified_content.replace(search_text, replace_text) else: # If exact block match fails, attempt a CSS-rule fallback using the replace_text try: import re updated_content = modified_content replaced_any_rule = False css_blocks = re.findall(r"([^{]+)\{([\s\S]*?)\}", replace_text, flags=re.MULTILINE) for selector_raw, body_raw in css_blocks: selector = selector_raw.strip() body = body_raw.strip() if not selector: continue pattern = re.compile(rf"({re.escape(selector)}\s*\{{)([\s\S]*?)(\}})") def _replace_rule(match): nonlocal replaced_any_rule replaced_any_rule = True prefix, existing_body, suffix = match.groups() first_line_indent = "" for line in existing_body.splitlines(): stripped = line.lstrip(" \t") if stripped: first_line_indent = line[: len(line) - len(stripped)] break if body: new_body_lines = [first_line_indent + line if line.strip() else line for line in body.splitlines()] new_body_text = "\n" + "\n".join(new_body_lines) + "\n" else: new_body_text = existing_body return f"{prefix}{new_body_text}{suffix}" updated_content, num_subs = pattern.subn(_replace_rule, updated_content, count=1) if replaced_any_rule: modified_content = updated_content else: print(f"Warning: Search text not found in content: {search_text[:100]}...") except Exception: print(f"Warning: Search text not found in content: {search_text[:100]}...") return modified_content
def apply_transformers_js_search_replace_changes(original_formatted_content: str, changes_text: str) -> str: """Apply search/replace changes to transformers.js formatted content (three files)""" if not changes_text.strip(): return original_formatted_content # Parse the original formatted content to get the three files files = parse_transformers_js_output(original_formatted_content) # Split the changes text into individual search/replace blocks blocks = [] current_block = "" lines = changes_text.split('\n') for line in lines: if line.strip() == SEARCH_START: if current_block.strip(): blocks.append(current_block.strip()) current_block = line + '\n' elif line.strip() == REPLACE_END: current_block += line + '\n' blocks.append(current_block.strip()) current_block = "" else: current_block += line + '\n' if current_block.strip(): blocks.append(current_block.strip()) # Process each block and apply changes to the appropriate file for block in blocks: if not block.strip(): continue # Parse the search/replace block lines = block.split('\n') search_lines = [] replace_lines = [] in_search = False in_replace = False target_file = None for line in lines: if line.strip() == SEARCH_START: in_search = True in_replace = False elif line.strip() == DIVIDER: in_search = False in_replace = True elif line.strip() == REPLACE_END: in_replace = False elif in_search: search_lines.append(line) elif in_replace: replace_lines.append(line) # Determine which file this change targets based on the search content if search_lines: search_text = '\n'.join(search_lines).strip() replace_text = '\n'.join(replace_lines).strip() # Check which file contains the search text if search_text in files['index.html']: target_file = 'index.html' elif search_text in files['index.js']: target_file = 'index.js' elif search_text in files['style.css']: target_file = 'style.css' # Apply the change to the target file if target_file and search_text in files[target_file]: files[target_file] = files[target_file].replace(search_text, replace_text) else: print(f"Warning: Search text not found in any transformers.js file: {search_text[:100]}...") # Reformat the modified files return format_transformers_js_output(files)
def send_to_sandbox(code): """Render HTML in a sandboxed iframe. Assumes full HTML is provided by prompts.""" html_doc = (code or "").strip() # For preview only: inline local file URLs as data URIs so the # data: iframe can load them. The original code (shown to the user) still contains file URLs. try: import re import base64 as _b64 import mimetypes as _mtypes import urllib.parse as _uparse def _file_url_to_data_uri(file_url: str) -> Optional[str]: try: parsed = _uparse.urlparse(file_url) path = _uparse.unquote(parsed.path) if not path: return None with open(path, 'rb') as _f: raw = _f.read() mime = _mtypes.guess_type(path)[0] or 'application/octet-stream' b64 = _b64.b64encode(raw).decode() return f"data:{mime};base64,{b64}" except Exception as e: print(f"[Sandbox] Failed to convert file URL to data URI: {str(e)}") return None def _repl_double(m): url = m.group(1) data_uri = _file_url_to_data_uri(url) return f'src="{data_uri}"' if data_uri else m.group(0) def _repl_single(m): url = m.group(1) data_uri = _file_url_to_data_uri(url) return f"src='{data_uri}'" if data_uri else m.group(0) html_doc = re.sub(r'src="(file:[^"]+)"', _repl_double, html_doc) html_doc = re.sub(r"src='(file:[^']+)'", _repl_single, html_doc) except Exception: # Best-effort; continue without inlining pass encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8') data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}" iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>' return iframe
def is_streamlit_code(code: str) -> bool: """Heuristic check to determine if Python code is a Streamlit app.""" if not code: return False lowered = code.lower() return ("import streamlit" in lowered) or ("from streamlit" in lowered) or ("st." in code and "streamlit" in lowered)
def clean_requirements_txt_content(content: str) -> str: """ Clean up requirements.txt content to remove markdown formatting. This function removes code blocks, markdown lists, headers, and other formatting that might be mistakenly included by LLMs. """ if not content: return content # First, remove code blocks if present if '```' in content: content = remove_code_block(content) # Process line by line to remove markdown formatting lines = content.split('\n') clean_lines = [] for line in lines: stripped_line = line.strip() # Skip empty lines if not stripped_line: continue # Skip lines that are markdown formatting if (stripped_line == '```' or stripped_line.startswith('```') or # Skip markdown headers (## Header) but keep comments (# comment) (stripped_line.startswith('#') and len(stripped_line) > 1 and stripped_line[1] != ' ') or stripped_line.startswith('**') or # Skip bold text stripped_line.startswith('===') or # Skip section dividers stripped_line.startswith('---') or # Skip horizontal rules # Skip common explanatory text patterns stripped_line.lower().startswith('here') or stripped_line.lower().startswith('this') or stripped_line.lower().startswith('the ') or stripped_line.lower().startswith('based on') or stripped_line.lower().startswith('dependencies') or stripped_line.lower().startswith('requirements')): continue # Handle markdown list items (- item or * item) if (stripped_line.startswith('- ') or stripped_line.startswith('* ')): # Extract the package name after the list marker stripped_line = stripped_line[2:].strip() if not stripped_line: continue # Keep lines that look like valid package specifications # Valid lines: package names, git+https://, comments starting with "# " if (stripped_line.startswith('# ') or # Valid comments stripped_line.startswith('git+') or # Git dependencies stripped_line[0].isalnum() or # Package names start with alphanumeric '==' in stripped_line or # Version specifications '>=' in stripped_line or # Version specifications '<=' in stripped_line or # Version specifications '~=' in stripped_line): # Version specifications clean_lines.append(stripped_line) result = '\n'.join(clean_lines) # Ensure it ends with a newline if result and not result.endswith('\n'): result += '\n' return result if result else "# No additional dependencies required\n"
def parse_multi_file_python_output(code: str) -> dict: """Parse multi-file Python output (Gradio/Streamlit) into separate files""" files = {} if not code: return files # Look for file separators like === filename.py === import re file_pattern = r'=== ([^=]+) ===' parts = re.split(file_pattern, code) if len(parts) > 1: # Multi-file format detected for i in range(1, len(parts), 2): if i + 1 < len(parts): filename = parts[i].strip() content = parts[i + 1].strip() # Clean up requirements.txt to remove markdown formatting if filename == 'requirements.txt': content = clean_requirements_txt_content(content) files[filename] = content else: # Single file - check if it's a space import or regular code if "IMPORTED PROJECT FROM HUGGING FACE SPACE" in code: # This is already a multi-file import, try to parse it lines = code.split('\n') current_file = None current_content = [] for line in lines: if line.startswith('=== ') and line.endswith(' ==='): # Save previous file if current_file and current_content: content = '\n'.join(current_content) # Clean up requirements.txt to remove markdown formatting if current_file == 'requirements.txt': content = clean_requirements_txt_content(content) files[current_file] = content # Start new file current_file = line[4:-4].strip() current_content = [] elif current_file: current_content.append(line) # Save last file if current_file and current_content: content = '\n'.join(current_content) # Clean up requirements.txt to remove markdown formatting if current_file == 'requirements.txt': content = clean_requirements_txt_content(content) files[current_file] = content else: # Single file code - determine appropriate filename if is_streamlit_code(code): files['streamlit_app.py'] = code elif 'import gradio' in code.lower() or 'from gradio' in code.lower(): files['app.py'] = code else: files['app.py'] = code return files
def format_multi_file_python_output(files: dict) -> str: """Format multiple Python files into the standard multi-file format""" if not files: return "" if len(files) == 1: # Single file - return as is return list(files.values())[0] # Multi-file format output = [] # Order files: main app first, then utils, models, config, requirements file_order = ['app.py', 'streamlit_app.py', 'main.py', 'utils.py', 'models.py', 'config.py', 'requirements.txt'] ordered_files = [] # Add files in preferred order for preferred_file in file_order: if preferred_file in files: ordered_files.append(preferred_file) # Add remaining files for filename in sorted(files.keys()): if filename not in ordered_files: ordered_files.append(filename) # Format output for filename in ordered_files: output.append(f"=== {filename} ===") # Clean up requirements.txt content if it's being formatted content = files[filename] if filename == 'requirements.txt': content = clean_requirements_txt_content(content) output.append(content) output.append("") # Empty line between files return '\n'.join(output)
def send_streamlit_to_stlite(code: str) -> str: """Render Streamlit code using stlite inside a sandboxed iframe for preview.""" # Build an HTML document that loads stlite and mounts the Streamlit app defined inline html_doc = ( """<!doctype html><html> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" /> <title>Streamlit Preview</title> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@stlite/browser@0.86.0/build/stlite.css\" /> <style>html,body{margin:0;padding:0;height:100%;} streamlit-app{display:block;height:100%;}</style> <script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/@stlite/browser@0.86.0/build/stlite.js\"></script> </head> <body> <streamlit-app>""" + (code or "") + """ </streamlit-app> </body></html>""" ) encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8') data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}" iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>' return iframe
def is_gradio_code(code: str) -> bool: """Heuristic check to determine if Python code is a Gradio app.""" if not code: return False lowered = code.lower() return ( "import gradio" in lowered or "from gradio" in lowered or "gr.Interface(" in code or "gr.Blocks(" in code )
def send_gradio_to_lite(code: str) -> str: """Render Gradio code using gradio-lite inside a sandboxed iframe for preview.""" html_doc = ( """<!doctype html><html> <head> <meta charset=\"UTF-8\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" /> <title>Gradio Preview</title> <script type=\"module\" crossorigin src=\"https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.js\"></script> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.css\" /> <style>html,body{margin:0;padding:0;height:100%;} gradio-lite{display:block;height:100%;}</style> </head> <body> <gradio-lite>""" + (code or "") + """ </gradio-lite> </body></html>""" ) encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8') data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}" iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>' return iframe
stop_generation = False
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817"""System prompts for different code generation modes in AnyCoder."""from .config import SEARCH_START, DIVIDER, REPLACE_END
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
**🚨 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 process
If an image is provided, analyze it and use the visual information to better understand the user's requirements.
Always respond with code that can be executed or rendered directly.
Generate complete, working HTML code that can be run immediately.
IMPORTANT: 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"""
# Stricter prompt for GLM-4.5V to ensure a complete, runnable HTML document with no escaped charactersGLM45V_HTML_SYSTEM_PROMPT = """You are an expert front-end developer.
**🚨 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 process
Output a COMPLETE, STANDALONE HTML document that renders directly in a browser.
Hard constraints:- DO NOT use React, ReactDOM, JSX, Babel, Vue, Angular, or any SPA framework.- Use ONLY plain HTML, CSS, and vanilla JavaScript.- Allowed external resources: Tailwind CSS CDN, Font Awesome CDN, Google Fonts.- Do NOT escape characters (no \\n, \\t, or escaped quotes). Output raw HTML/JS/CSS.Structural requirements:- Include <!DOCTYPE html>, <html>, <head>, and <body> with proper nesting- Include required <link> tags for any CSS you reference (e.g., Tailwind, Font Awesome, Google Fonts)- Keep everything in ONE file; inline CSS/JS as needed
Generate complete, working HTML code that can be run immediately.
IMPORTANT: 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"""
TRANSFORMERS_JS_SYSTEM_PROMPT = """You are an expert web developer creating a transformers.js application. You will generate THREE separate files: index.html, index.js, and style.css.
**🚨 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 process
IMPORTANT: You MUST output ALL THREE files in the following format:
```html<!-- index.html content here -->```
```javascript// index.js content here```
```css/* style.css content here */```
Requirements:1. Create a modern, responsive web application using transformers.js2. Use the transformers.js library for AI/ML functionality3. Create a clean, professional UI with good user experience4. Make the application fully responsive for mobile devices5. Use modern CSS practices and JavaScript ES6+ features6. Include proper error handling and loading states7. Follow accessibility best practices
Library import (required): Add the following snippet to index.html to import transformers.js:<script type="module"> import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.3';</script>
Device Options: By default, transformers.js runs on CPU (via WASM). For better performance, you can run models on GPU using WebGPU:- CPU (default): const pipe = await pipeline('task', 'model-name');- GPU (WebGPU): const pipe = await pipeline('task', 'model-name', { device: 'webgpu' });
Consider providing users with a toggle option to choose between CPU and GPU execution based on their browser's WebGPU support.
The index.html should contain the basic HTML structure and link to the CSS and JS files.The index.js should contain all the JavaScript logic including transformers.js integration.The style.css should contain all the styling for the application.
Generate complete, working code files as shown above.
IMPORTANT: 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"""
STREAMLIT_SYSTEM_PROMPT = """You are an expert Streamlit developer. Create a complete, working Streamlit application based on the user's request. Generate all necessary code to make the application functional and runnable.
## Multi-File Application Structure
When creating Streamlit applications, you MUST organize your code into multiple files for proper deployment:
**File Organization (CRITICAL - Always Include These):**- `Dockerfile` - Docker configuration for deployment (REQUIRED)- `streamlit_app.py` - Main application entry point (REQUIRED)- `requirements.txt` - Python dependencies (REQUIRED)- `utils.py` - Utility functions and helpers (optional)- `models.py` - Model loading and inference functions (optional)- `config.py` - Configuration and constants (optional)- `pages/` - Additional pages for multi-page apps (optional)- Additional modules as needed (e.g., `data_processing.py`, `components.py`)
**🚨 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 process- Only generate the code files listed above
**Output Format for Streamlit Apps:**You MUST use this exact format and ALWAYS include Dockerfile, streamlit_app.py, and requirements.txt:
```=== Dockerfile ===[Dockerfile content]
=== streamlit_app.py ===[main application code]
=== requirements.txt ===[dependencies]
=== utils.py ===[utility functions - optional]```
**🚨 CRITICAL: Dockerfile Requirements (MANDATORY for HuggingFace Spaces)**Your Dockerfile MUST follow these exact specifications:- Use Python 3.11+ base image (e.g., FROM python:3.11-slim)- Set up a user with ID 1000 for proper permissions: ``` RUN useradd -m -u 1000 user USER user ENV HOME=/home/user \\ PATH=/home/user/.local/bin:$PATH WORKDIR $HOME/app ```- ALWAYS use --chown=user with COPY and ADD commands: ``` COPY --chown=user requirements.txt . COPY --chown=user . . ```- Install dependencies: RUN pip install --no-cache-dir -r requirements.txt- Expose port 7860 (HuggingFace Spaces default): EXPOSE 7860- Start with: CMD ["streamlit", "run", "streamlit_app.py", "--server.port=7860", "--server.address=0.0.0.0"]
**Example Dockerfile structure (USE THIS AS TEMPLATE):**```dockerfileFROM python:3.11-slim
# Set up user with ID 1000RUN useradd -m -u 1000 userUSER userENV HOME=/home/user \\ PATH=/home/user/.local/bin:$PATH
# Set working directoryWORKDIR $HOME/app
# Copy requirements file with proper ownershipCOPY --chown=user requirements.txt .
# Install dependenciesRUN pip install --no-cache-dir -r requirements.txt
# Copy application files with proper ownershipCOPY --chown=user . .
# Expose port 7860EXPOSE 7860
# Start Streamlit appCMD ["streamlit", "run", "streamlit_app.py", "--server.port=7860", "--server.address=0.0.0.0"]```
**🚨 CRITICAL: requirements.txt Formatting Rules**- Output ONLY plain text package names, one per line- Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)- Do NOT add explanatory text or descriptions- Do NOT wrap in code blocks- Just raw package names as they would appear in a real requirements.txt file- Example of CORRECT format: streamlit pandas numpy- Example of INCORRECT format (DO NOT DO THIS): ``` streamlit # For web interface **Core dependencies:** - pandas ```
**Multi-Page Apps:**For multi-page Streamlit apps, use the pages/ directory structure:```=== Dockerfile ===[Dockerfile content]
=== streamlit_app.py ===[main page]
=== requirements.txt ===[dependencies]
=== pages/1_📊_Analytics.py ===[analytics page]
=== pages/2_⚙️_Settings.py ===[settings page]```
Requirements:1. ALWAYS include Dockerfile, streamlit_app.py, and requirements.txt in your output2. Create a modern, responsive Streamlit application3. Use appropriate Streamlit components and layouts4. Include proper error handling and loading states5. Follow Streamlit best practices for performance6. Use caching (@st.cache_data, @st.cache_resource) appropriately7. Include proper session state management when needed8. Make the UI intuitive and user-friendly9. Add helpful tooltips and documentation
IMPORTANT: 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"""
REACT_SYSTEM_PROMPT = """You are an expert React and Next.js developer creating a modern Next.js application.
**🚨 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 process
You will generate a Next.js project with TypeScript/JSX components. Follow this exact structure:
Project Structure:- Dockerfile (Docker configuration for deployment)- package.json (dependencies and scripts)- next.config.js (Next.js configuration)- postcss.config.js (PostCSS configuration)- tailwind.config.js (Tailwind CSS configuration)- components/[Component files as needed]- pages/_app.js (Next.js app wrapper)- pages/index.js (home page)- pages/api/[API routes as needed]- styles/globals.css (global styles)
Output format (CRITICAL):- Return ONLY a series of file sections, each starting with a filename line: === Dockerfile === ...file content...
=== package.json === ...file content...
(repeat for all files)- Do NOT wrap files in Markdown code fences or use === markers inside file content
CRITICAL Requirements:1. Always include a Dockerfile configured for Node.js deployment (see Dockerfile Requirements below)2. Use Next.js with TypeScript/JSX (.jsx files for components)3. **USE TAILWIND CSS FOR ALL STYLING** - Avoid inline styles completely (in postcss.config.js and tailwind.config.js)4. Create necessary components in the components/ directory5. Create API routes in pages/api/ directory for backend logic6. pages/_app.js should import and use globals.css7. pages/index.js should be the main entry point8. Keep package.json with essential dependencies9. Use modern React patterns and best practices10. Make the application fully responsive using Tailwind classes11. Include proper error handling and loading states12. Follow accessibility best practices13. Configure next.config.js properly for HuggingFace Spaces deployment14. **NEVER use inline style={{}} objects - always use Tailwind className instead**
🚨 CRITICAL JSX SYNTAX RULES - FOLLOW EXACTLY:
**RULE 1: Style objects MUST have proper closing braces }}**Every style={{ must have a matching }} before any other props or />
**RULE 2: ALWAYS use Tailwind CSS classes instead of inline styles**- Use className="..." for styling- Only use inline styles if absolutely necessary- Inline styles are error-prone and should be avoided
**CORRECT Examples:**```jsx// ✅ Using Tailwind (PREFERRED)<textarea className="w-full p-3 min-h-[48px] max-h-[120px] rounded-lg border" value={message} onChange={(e) => setMessage(e.target.value)} placeholder="Type here"/>
// ✅ Inline style (if needed) - note the }} before other props<textarea style={{ width: '100%', padding: '12px', minHeight: '48px' }} value={message} onChange={(e) => setMessage(e.target.value)}/>```
**WRONG Examples:**```jsx// ❌ WRONG - Missing closing braces }}<textarea style={{ minHeight: '48px', maxHeight: '120px' />
// ❌ WRONG - Event handler inside style object<textarea style={{ width: '100%' onChange={(e) => {}} // Missing }}/>```
**RULE 3: Validation Checklist**Before outputting JSX code, verify:- [ ] All style={{ have matching }}- [ ] No event handlers inside style objects- [ ] Prefer Tailwind classes over inline styles- [ ] All JSX elements are properly closed
next.config.js Requirements:- Must be configured to work on any host (0.0.0.0)- Should not have hardcoded localhost references- Example minimal configuration:```javascript/** @type {import('next').NextConfig} */const nextConfig = { reactStrictMode: true, // Allow the app to work on HuggingFace Spaces output: 'standalone',}
module.exports = nextConfig```
Dockerfile Requirements (CRITICAL for HuggingFace Spaces):- Use Node.js 18+ base image (e.g., FROM node:18-slim)- Use the existing 'node' user (UID 1000 already exists in node base images): ``` USER node ENV HOME=/home/node \\ PATH=/home/node/.local/bin:$PATH WORKDIR /home/node/app ```- ALWAYS use --chown=node:node with COPY and ADD commands: ``` COPY --chown=node:node package*.json ./ COPY --chown=node:node . . ```- Install dependencies: RUN npm install- Build the app: RUN npm run build- Expose port 7860 (HuggingFace Spaces default): EXPOSE 7860- Start with: CMD ["npm", "start", "--", "-p", "7860"]
Example Dockerfile structure:```dockerfileFROM node:18-slim
# Use the existing node user (UID 1000)USER node
# Set environment variablesENV HOME=/home/node \\ PATH=/home/node/.local/bin:$PATH
# Set working directoryWORKDIR /home/node/app
# Copy package files with proper ownershipCOPY --chown=node:node package*.json ./
# Install dependenciesRUN npm install
# Copy rest of the application with proper ownershipCOPY --chown=node:node . .
# Build the Next.js appRUN npm run build
# Expose port 7860EXPOSE 7860
# Start the application on port 7860CMD ["npm", "start", "--", "-p", "7860"]```
IMPORTANT: 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"""
REACT_FOLLOW_UP_SYSTEM_PROMPT = """You are an expert React and Next.js developer modifying an existing Next.js application.The user wants to apply changes based on their request.You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.
🚨 CRITICAL JSX SYNTAX RULES - FOLLOW EXACTLY:
**RULE 1: Style objects MUST have proper closing braces }}**Every style={{ must have a matching }} before any other props or />
**RULE 2: ALWAYS use Tailwind CSS classes instead of inline styles**- Use className="..." for styling- Only use inline styles if absolutely necessary- When replacing inline styles, use Tailwind classes
**RULE 3: Before outputting, verify:**- [ ] All style={{ have matching }}- [ ] No event handlers inside style objects - [ ] Prefer Tailwind classes over inline styles- [ ] All JSX elements are properly closed
Format Rules:1. Start with <<<<<<< SEARCH2. Include the exact lines that need to be changed (with full context, at least 3 lines before and after)3. Follow with =======4. Include the replacement lines5. End with >>>>>>> REPLACE6. Generate multiple blocks if multiple sections need changes
IMPORTANT: 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 prompts will be dynamically populated by update_gradio_system_prompts()GRADIO_SYSTEM_PROMPT = ""GRADIO_SYSTEM_PROMPT_WITH_SEARCH = ""
# GRADIO_SYSTEM_PROMPT_WITH_SEARCH will be dynamically populated by update_gradio_system_prompts()
# 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.txt
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.
**🚨 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 process
IMPORTANT: 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"""
# Multi-page static HTML project prompt (generic, production-style structure)MULTIPAGE_HTML_SYSTEM_PROMPT = """You are an expert front-end developer.
**🚨 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 process
Create a production-ready MULTI-PAGE website using ONLY HTML, CSS, and vanilla JavaScript. Do NOT use SPA frameworks.
Output MUST be a multi-file project with at least:- index.html (home)- about.html (secondary page)- contact.html (secondary page)- assets/css/styles.css (global styles)- assets/js/main.js (site-wide JS)
Navigation requirements:- A consistent header with a nav bar on every page- Highlight current nav item- Responsive layout and accessibility best practices
Output format requirements (CRITICAL):- Return ONLY a series of file sections, each starting with a filename line: === index.html === ...file content...
=== about.html === ...file content...
(repeat for all files)- Do NOT wrap files in Markdown code fences- Use relative paths between files (e.g., assets/css/styles.css)
General requirements:- Use modern, semantic HTML- Mobile-first responsive design- Include basic SEO meta tags in <head>- Include a footer on all pages- Avoid external CSS/JS frameworks (optional: CDN fonts/icons allowed)
IMPORTANT: 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"""
# Dynamic multi-page (model decides files) promptsDYNAMIC_MULTIPAGE_HTML_SYSTEM_PROMPT = """You are an expert front-end developer.
**🚨 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 process
Create a production-ready website using ONLY HTML, CSS, and vanilla JavaScript. Do NOT use SPA frameworks.
File selection policy:- Generate ONLY the files actually needed for the user's request.- Include at least one HTML entrypoint (default: index.html) unless the user explicitly requests a non-HTML asset only.- If any local asset (CSS/JS/image) is referenced, include that file in the output.- Use relative paths between files (e.g., assets/css/styles.css).
Output format (CRITICAL):- Return ONLY a series of file sections, each starting with a filename line: === index.html === ...file content...
=== assets/css/styles.css === ...file content...
(repeat for all files)- Do NOT wrap files in Markdown code fences
General requirements:- Use modern, semantic HTML- Mobile-first responsive design- Include basic SEO meta tags in <head> for the entrypoint- Include a footer on all major pages when multiple pages are present- Avoid external CSS/JS frameworks (optional: CDN fonts/icons allowed)
IMPORTANT: 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"""
# Follow-up system prompt for modifying existing HTML filesFollowUpSystemPrompt = f"""You are an expert web developer modifying an existing project.The user wants to apply changes based on their request.You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.
IMPORTANT: When the user reports an ERROR MESSAGE, analyze it carefully to determine which file needs fixing:- ImportError/ModuleNotFoundError → Fix requirements.txt by adding missing packages- Syntax errors in Python code → Fix app.py or the main Python file- HTML/CSS/JavaScript errors → Fix the respective HTML/CSS/JS files- Configuration errors → Fix config files, Docker files, etc.
For Python applications (Gradio/Streamlit), the project structure typically includes:- app.py or streamlit_app.py (main application file)- requirements.txt (dependencies)- utils.py (utility functions)- models.py (model loading and inference)- config.py (configuration)- pages/ (for multi-page Streamlit apps)- Other supporting files as needed
**🚨 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 process
For multi-file projects, identify which specific file needs modification based on the user's request:- Main application logic → app.py or streamlit_app.py- Helper functions → utils.py- Model-related code → models.py- Configuration changes → config.py- Dependencies → requirements.txt- New pages → pages/filename.py
Format Rules:1. Start with {SEARCH_START}2. Provide the exact lines from the current code that need to be replaced.3. Use {DIVIDER} to separate the search block from the replacement.4. Provide the new lines that should replace the original lines.5. End with {REPLACE_END}6. You can use multiple SEARCH/REPLACE blocks if changes are needed in different parts of the file.7. To insert code, use an empty SEARCH block (only {SEARCH_START} and {DIVIDER} on their lines) if inserting at the very beginning, otherwise provide the line *before* the insertion point in the SEARCH block and include that line plus the new lines in the REPLACE block.8. To delete code, provide the lines to delete in the SEARCH block and leave the REPLACE block empty (only {DIVIDER} and {REPLACE_END} on their lines).9. IMPORTANT: The SEARCH block must *exactly* match the current code, including indentation and whitespace.10. For multi-file projects, specify which file you're modifying by starting with the filename before the search/replace block.
CSS Changes Guidance: - When changing a CSS property that conflicts with other properties (e.g., replacing a gradient text with a solid color), replace the entire CSS rule for that selector instead of only adding the new property. For example, replace the full `.hero h1 { ... }` block, removing `background-clip` and `color: transparent` when setting `color: #fff`. - Ensure search blocks match the current code exactly (spaces, indentation, and line breaks) so replacements apply correctly.
Example Modifying Code:```Some explanation...{SEARCH_START} <h1>Old Title</h1>{DIVIDER} <h1>New Title</h1>{REPLACE_END}{SEARCH_START} </body>{DIVIDER} <script>console.log("Added script");</script> </body>{REPLACE_END}```
Example Fixing Dependencies (requirements.txt):```Adding missing dependency to fix ImportError...=== requirements.txt ==={SEARCH_START}gradiostreamlit{DIVIDER}gradiostreamlitmistral-common{REPLACE_END}```
Example Deleting Code:```Removing the paragraph...{SEARCH_START} <p>This paragraph will be deleted.</p>{DIVIDER}{REPLACE_END}```
IMPORTANT: Always ensure "Built with anycoder" appears as clickable text in the header/top section linking to https://huggingface.co/spaces/akhaliq/anycoder - if it's missing from the existing code, add it; if it exists, preserve it.
CRITICAL: For imported spaces that lack anycoder attribution, you MUST add it as part of your modifications. Add it to the header/navigation area as clickable text linking to https://huggingface.co/spaces/akhaliq/anycoder"""
# Follow-up system prompt for modifying existing Gradio applicationsGradioFollowUpSystemPrompt = """You are an expert Gradio developer modifying an existing Gradio application.The user wants to apply changes based on their request.
🚨 CRITICAL OUTPUT RULES:- DO NOT use <think> tags or thinking blocks in your output- DO NOT use [TOOL_CALL] or any tool call markers- Generate ONLY the requested code files- No explanatory text outside the code blocks
🚨 CRITICAL INSTRUCTION: You MUST maintain the original multi-file structure when making modifications. ❌ Do NOT use SEARCH/REPLACE blocks. ❌ Do NOT output everything in one combined block.✅ Instead, output the complete modified files using the EXACT same multi-file format as the original generation.
**MANDATORY Output Format for Modified Gradio Apps:**You MUST use this exact format with file separators. DO NOT deviate from this format:
=== app.py ===[complete modified app.py content]
**CRITICAL FORMATTING RULES:**- ALWAYS start each file with exactly "=== filename ===" (three equals signs before and after)- NEVER combine files into one block- NEVER use SEARCH/REPLACE blocks like <<<<<<< SEARCH- ALWAYS include app.py if it needs changes- Only include other files (utils.py, models.py, etc.) if they exist and need changes- Each file section must be complete and standalone- The format MUST match the original multi-file structure exactly
**🚨 CRITICAL: DO NOT GENERATE requirements.txt or README.md**- requirements.txt is automatically generated from your app.py imports- README.md is automatically provided by the template- Do NOT include requirements.txt or README.md in your output unless the user specifically asks to modify them- The system will automatically extract imports from app.py and generate requirements.txt- Generating a README.md will break the deployment process- This prevents unnecessary changes to dependencies and documentation
**IF User Specifically Asks to Modify requirements.txt:**- Output ONLY plain text package names, one per line- Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)- Do NOT add explanatory text or descriptions- Do NOT wrap in code blocks- Just raw package names as they would appear in a real requirements.txt file- Example of CORRECT format: gradio torch transformers- Example of INCORRECT format (DO NOT DO THIS): ``` gradio # For web interface **Core dependencies:** - torch ```
**File Modification Guidelines:**- Only output files that actually need changes- If a file doesn't need modification, don't include it in the output- Maintain the exact same file structure as the original- Preserve all existing functionality unless specifically asked to change it- Keep all imports, dependencies, and configurations intact unless modification is requested
**Common Modification Scenarios:**- Adding new features → Modify app.py and possibly utils.py- Fixing bugs → Modify the relevant file (usually app.py)- Adding dependencies → Modify requirements.txt- UI improvements → Modify app.py- Performance optimizations → Modify app.py and/or utils.py
**ZeroGPU and Performance:**- Maintain all existing @spaces.GPU decorators- Keep AoT compilation if present- Preserve all performance optimizations- Add ZeroGPU decorators for new GPU-dependent functions
**MCP Server Support:**- If the user requests MCP functionality or tool calling capabilities: 1. Add `mcp_server=True` to the `.launch()` method if not present 2. Ensure `gradio[mcp]` is in requirements.txt (not just `gradio`) 3. Add detailed docstrings with Args sections to all functions 4. Add type hints to all function parameters- Preserve existing MCP configurations if already present- When adding new tools, follow MCP docstring format with Args and Returns sections
IMPORTANT: Always ensure "Built with anycoder" appears as clickable text in the header/top section linking to https://huggingface.co/spaces/akhaliq/anycoder - if it's missing from the existing code, add it; if it exists, preserve it.
CRITICAL: For imported spaces that lack anycoder attribution, you MUST add it as part of your modifications. Add it to the header/navigation area as clickable text linking to https://huggingface.co/spaces/akhaliq/anycoder"""
# Follow-up system prompt for modifying existing transformers.js applicationsTransformersJSFollowUpSystemPrompt = f"""You are an expert web developer modifying an existing transformers.js application.The user wants to apply changes based on their request.You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.
IMPORTANT: When the user reports an ERROR MESSAGE, analyze it carefully to determine which file needs fixing:- JavaScript errors/module loading issues → Fix index.js- HTML rendering/DOM issues → Fix index.html- Styling/visual issues → Fix style.css- CDN/library loading errors → Fix script tags in index.html
The transformers.js application consists of three files: index.html, index.js, and style.css.When making changes, specify which file you're modifying by starting your search/replace blocks with the file name.
**🚨 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 process
Format Rules:1. Start with {SEARCH_START}2. Provide the exact lines from the current code that need to be replaced.3. Use {DIVIDER} to separate the search block from the replacement.4. Provide the new lines that should replace the original lines.5. End with {REPLACE_END}6. You can use multiple SEARCH/REPLACE blocks if changes are needed in different parts of the file.7. To insert code, use an empty SEARCH block (only {SEARCH_START} and {DIVIDER} on their lines) if inserting at the very beginning, otherwise provide the line *before* the insertion point in the SEARCH block and include that line plus the new lines in the REPLACE block.8. To delete code, provide the lines to delete in the SEARCH block and leave the REPLACE block empty (only {DIVIDER} and {REPLACE_END} on their lines).9. IMPORTANT: The SEARCH block must *exactly* match the current code, including indentation and whitespace.
Example Modifying HTML:```Changing the title in index.html...=== index.html ==={SEARCH_START} <title>Old Title</title>{DIVIDER} <title>New Title</title>{REPLACE_END}```
Example Modifying JavaScript:```Adding a new function to index.js...=== index.js ==={SEARCH_START}// Existing code{DIVIDER}// Existing code
function newFunction() {{ console.log("New function added");}}{REPLACE_END}```
Example Modifying CSS:```Changing background color in style.css...=== style.css ==={SEARCH_START}body {{ background-color: white;}}{DIVIDER}body {{ background-color: #f0f0f0;}}{REPLACE_END}```Example Fixing Library Loading Error:```Fixing transformers.js CDN loading error...=== index.html ==={SEARCH_START}<script type="module" src="https://cdn.jsdelivr.net/npm/@xenova/transformers@2.6.0"></script>{DIVIDER}<script type="module" src="https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2"></script>{REPLACE_END}```
IMPORTANT: Always ensure "Built with anycoder" appears as clickable text in the header/top section linking to https://huggingface.co/spaces/akhaliq/anycoder - if it's missing from the existing code, add it; if it exists, preserve it.
CRITICAL: For imported spaces that lack anycoder attribution, you MUST add it as part of your modifications. Add it to the header/navigation area as clickable text linking to https://huggingface.co/spaces/akhaliq/anycoder"""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257"""Gradio theme configurations for AnyCoder.Provides multiple theme options with different visual styles."""import osimport gradio as gr
def get_saved_theme(): """Get the saved theme preference from file""" try: if os.path.exists('.theme_preference'): with open('.theme_preference', 'r') as f: return f.read().strip() except: pass return "Developer"def save_theme_preference(theme_name): """Save theme preference to file""" try: with open('.theme_preference', 'w') as f: f.write(theme_name) except: pass
THEME_CONFIGS = { "Default": { "theme": gr.themes.Default(), "description": "Gradio's standard theme with clean orange accents" }, "Base": { "theme": gr.themes.Base( primary_hue="blue", secondary_hue="slate", neutral_hue="slate", text_size="sm", spacing_size="sm", radius_size="md" ), "description": "Minimal foundation theme with blue accents" }, "Soft": { "theme": gr.themes.Soft( primary_hue="emerald", secondary_hue="emerald", neutral_hue="slate", text_size="sm", spacing_size="md", radius_size="lg" ), "description": "Gentle rounded theme with soft emerald colors" }, "Monochrome": { "theme": gr.themes.Monochrome( primary_hue="slate", secondary_hue="slate", neutral_hue="slate", text_size="sm", spacing_size="sm", radius_size="sm" ), "description": "Elegant black and white design" }, "Glass": { "theme": gr.themes.Glass( primary_hue="blue", secondary_hue="blue", neutral_hue="slate", text_size="sm", spacing_size="md", radius_size="lg" ), "description": "Modern glassmorphism with blur effects" }, "Dark Ocean": { "theme": gr.themes.Base( primary_hue="blue", secondary_hue="slate", neutral_hue="slate", text_size="sm", spacing_size="sm", radius_size="md" ).set( body_background_fill="#0f172a", body_background_fill_dark="#0f172a", background_fill_primary="#3b82f6", background_fill_secondary="#1e293b", border_color_primary="#334155", block_background_fill="#1e293b", block_border_color="#334155", body_text_color="#f1f5f9", body_text_color_dark="#f1f5f9", block_label_text_color="#f1f5f9", block_label_text_color_dark="#f1f5f9", block_title_text_color="#f1f5f9", block_title_text_color_dark="#f1f5f9", input_background_fill="#0f172a", input_background_fill_dark="#0f172a", input_border_color="#334155", input_border_color_dark="#334155", button_primary_background_fill="#3b82f6", button_primary_border_color="#3b82f6", button_secondary_background_fill="#334155", button_secondary_border_color="#475569" ), "description": "Deep blue dark theme perfect for coding" }, "Cyberpunk": { "theme": gr.themes.Base( primary_hue="fuchsia", secondary_hue="cyan", neutral_hue="slate", text_size="sm", spacing_size="sm", radius_size="none", font="Orbitron" ).set( body_background_fill="#0a0a0f", body_background_fill_dark="#0a0a0f", background_fill_primary="#ff10f0", background_fill_secondary="#1a1a2e", border_color_primary="#00f5ff", block_background_fill="#1a1a2e", block_border_color="#00f5ff", body_text_color="#00f5ff", body_text_color_dark="#00f5ff", block_label_text_color="#ff10f0", block_label_text_color_dark="#ff10f0", block_title_text_color="#ff10f0", block_title_text_color_dark="#ff10f0", input_background_fill="#0a0a0f", input_background_fill_dark="#0a0a0f", input_border_color="#00f5ff", input_border_color_dark="#00f5ff", button_primary_background_fill="#ff10f0", button_primary_border_color="#ff10f0", button_secondary_background_fill="#1a1a2e", button_secondary_border_color="#00f5ff" ), "description": "Futuristic neon cyber aesthetics" }, "Forest": { "theme": gr.themes.Soft( primary_hue="emerald", secondary_hue="green", neutral_hue="emerald", text_size="sm", spacing_size="md", radius_size="lg" ).set( body_background_fill="#f0fdf4", body_background_fill_dark="#064e3b", background_fill_primary="#059669", background_fill_secondary="#ecfdf5", border_color_primary="#bbf7d0", block_background_fill="#ffffff", block_border_color="#d1fae5", body_text_color="#064e3b", body_text_color_dark="#f0fdf4", block_label_text_color="#064e3b", block_label_text_color_dark="#f0fdf4", block_title_text_color="#059669", block_title_text_color_dark="#10b981" ), "description": "Nature-inspired green earth tones" }, "High Contrast": { "theme": gr.themes.Base( primary_hue="yellow", secondary_hue="slate", neutral_hue="slate", text_size="lg", spacing_size="lg", radius_size="sm" ).set( body_background_fill="#ffffff", body_background_fill_dark="#ffffff", background_fill_primary="#000000", background_fill_secondary="#ffffff", border_color_primary="#000000", block_background_fill="#ffffff", block_border_color="#000000", body_text_color="#000000", body_text_color_dark="#000000", block_label_text_color="#000000", block_label_text_color_dark="#000000", block_title_text_color="#000000", block_title_text_color_dark="#000000", input_background_fill="#ffffff", input_background_fill_dark="#ffffff", input_border_color="#000000", input_border_color_dark="#000000", button_primary_background_fill="#ffff00", button_primary_border_color="#000000", button_secondary_background_fill="#ffffff", button_secondary_border_color="#000000" ), "description": "Accessibility-focused high visibility" }, "Developer": { "theme": gr.themes.Base( primary_hue="blue", secondary_hue="slate", neutral_hue="slate", text_size="sm", spacing_size="sm", radius_size="sm", font="Consolas" ).set( # VS Code exact colors body_background_fill="#1e1e1e", # VS Code editor background body_background_fill_dark="#1e1e1e", background_fill_primary="#007acc", # VS Code blue accent background_fill_secondary="#252526", # VS Code sidebar background border_color_primary="#3e3e42", # VS Code border color block_background_fill="#252526", # VS Code panel background block_border_color="#3e3e42", # VS Code subtle borders body_text_color="#cccccc", # VS Code default text body_text_color_dark="#cccccc", block_label_text_color="#cccccc", block_label_text_color_dark="#cccccc", block_title_text_color="#ffffff", # VS Code active text block_title_text_color_dark="#ffffff", input_background_fill="#2d2d30", # VS Code input background input_background_fill_dark="#2d2d30", input_border_color="#3e3e42", # VS Code input border input_border_color_dark="#3e3e42", input_border_color_focus="#007acc", # VS Code focus border input_border_color_focus_dark="#007acc", button_primary_background_fill="#007acc", # VS Code button blue button_primary_border_color="#007acc", button_primary_background_fill_hover="#0e639c", # VS Code button hover button_secondary_background_fill="#2d2d30", button_secondary_border_color="#3e3e42", button_secondary_text_color="#cccccc" ), "description": "Authentic VS Code dark theme with exact color matching" }}
# Additional theme information for developersTHEME_FEATURES = { "Default": ["Orange accents", "Clean layout", "Standard Gradio look"], "Base": ["Blue accents", "Minimal styling", "Clean foundation"], "Soft": ["Rounded corners", "Emerald colors", "Comfortable viewing"], "Monochrome": ["Black & white", "High elegance", "Timeless design"], "Glass": ["Glassmorphism", "Blur effects", "Translucent elements"], "Dark Ocean": ["Deep blue palette", "Dark theme", "Easy on eyes"], "Cyberpunk": ["Neon cyan/magenta", "Futuristic fonts", "Cyber vibes"], "Forest": ["Nature inspired", "Green tones", "Organic rounded"], "High Contrast": ["Black/white/yellow", "High visibility", "Accessibility"], "Developer": ["Authentic VS Code colors", "Consolas/Monaco fonts", "Exact theme matching"]}
# Load saved theme and apply itcurrent_theme_name = get_saved_theme()current_theme = THEME_CONFIGS[current_theme_name]["theme"]
anycoder_app/__init__.pyDeleted-27
anycoder_app/agent.pyDeleted-234
anycoder_app/config.pyDeleted-190
anycoder_app/deploy.pyDeleted
anycoder_app/docs_manager.pyDeleted-1484
anycoder_app/models.pyDeleted-361
anycoder_app/parsers.pyDeleted-1111
anycoder_app/prompts.pyDeleted-817
anycoder_app/themes.pyDeleted-257
anycoder_app/ui.pyDeleted
app.py.backupDeleted