""" Multi-Agent Builder — HuggingFace Spaces / Gradio App ===================================================== Strategy → Design → Build → Code Review New in this version: • NVIDIA NIM with automatic multi-model health checking and fallback • Image reference upload — attach a screenshot/mockup for the agents to study • Vision support for Anthropic Claude and NVIDIA vision models • Fixed code-block filename extraction (handles all model output styles) • Background NVIDIA health check on startup """ import gradio as gr import os import re import zipfile import tempfile import time import threading from pathlib import Path from agents import ( run_agent, run_agent_with_fallback, _encode_image, PROVIDER_DEFAULTS, NVIDIA_TEXT_MODELS, NVIDIA_CODE_MODELS, NVIDIA_VISION_MODELS, run_nvidia_health_check, reset_health_cache, get_health_summary, get_best_nvidia_model, ) # ── System prompts ──────────────────────────────────────────────────────────── SYSTEM_PROMPTS = { "strategy": """You are a senior product strategist and solutions architect with 15+ years of experience. Your job is to take a user's build request and produce a clear, opinionated strategy document. Your output must include: 1. **Goal Summary** — What are we building and why? (2-3 sentences) 2. **Core Features** — Bullet list of the 4-6 most important features to build 3. **Tech Stack Decision** — Recommended languages, frameworks, and libraries with brief justification 4. **Out of Scope** — What we are explicitly NOT building in v1 5. **Risks & Assumptions** — 2-3 key risks or assumptions the builder should know about 6. **Success Criteria** — How do we know this is done and working? Be direct and opinionated. Don't hedge excessively. Make decisions. Format with clear markdown headers and bullet points. If a reference image is provided, analyse it carefully and incorporate relevant details into your strategy.""", "design": """You are a senior UX designer and software architect. You receive a strategy document and translate it into a concrete technical design spec. Your output must include: 1. **Architecture Overview** — How the system is structured (components, data flow) 2. **File Structure** — The exact folder and file layout the builder should create 3. **Component / Module Breakdown** — What each file/module does 4. **Data Models** — Key data structures, types, or schemas 5. **UX Flow** (if applicable) — User journey, key screens or interactions 6. **API / Interface Design** (if applicable) — Endpoints, function signatures, or contracts 7. **Edge Cases to Handle** — At least 3 edge cases the builder must account for Be precise. Give the builder everything they need to start coding immediately. Format with clear markdown headers. Use code blocks for schemas and file trees. If a reference image is provided, describe its layout and incorporate it into the design spec.""", "builder": """You are an expert full-stack developer. You write clean, production-quality code. You receive a strategy document and a design spec, and you build the thing. CRITICAL OUTPUT RULES — read carefully, every rule is enforced: 1. OUTPUT FORMAT — every single file MUST use this EXACT header line: ```filename: path/to/file.ext (file contents here — complete, no truncation) ``` The word `filename:` must appear at the start of the fence label. Nothing else is accepted. 2. COMPLETENESS — no placeholders, no "# TODO", no "..." ellipsis, no stubs. Every function must have a real implementation. 3. WEB APPS — prefer a single self-contained `index.html` with all CSS and JS inline. This lets the user open it directly in their browser without a server. Only split into separate files (style.css, script.js) if the design explicitly requires it. Use CDN links (cdnjs.cloudflare.com) for any external libraries — do NOT assume npm. 4. PYTHON APPS — include a `requirements.txt` and a clear `README.md` with run instructions. The script must work with `python script.py` or `python -m module`. 5. TESTABILITY — the output must be immediately runnable: - Web: open index.html in a browser → it works - Python: `pip install -r requirements.txt && python app.py` → it works - No missing assets, no broken imports, no placeholder API keys needed to see the UI. 6. REFERENCE IMAGE — if one was provided, match its layout, colour scheme, and UI elements as closely as possible in your implementation. 7. STYLING — always import Bootstrap 5 from CDN as the FIRST stylesheet in
: Use Bootstrap components (cards, buttons, forms, navbar, grid) and utility classes throughout. Never output unstyled or bare HTML. Every section should look clean and modern out of the box. 8. PROGRESSIVE DISCLOSURE — interactive sections (canvas editors, image previews, results panels) MUST be hidden by default using Bootstrap's d-none class and revealed via JavaScript only when relevant data is available. For example: show the crop UI only after an image is uploaded, show the download button only after processing is complete. An empty canvas taking up 600px of blank space on first load is a bug, not a feature. Do not truncate any file. If a file is long, write it completely.""", "reviewer": """You are a staff-level engineer conducting a rigorous code review. Your job is to find real problems — not nitpick style for its own sake. Your review must cover: 1. **Correctness** — Does the code actually do what it's supposed to? Any logic bugs? 2. **Security** — Any obvious vulnerabilities? (injection, hardcoded secrets, unsafe eval, etc.) 3. **Error Handling** — Are failures handled gracefully? 4. **Performance** — Any obvious inefficiencies? 5. **Missing Pieces** — Anything required but not implemented? 6. **Testability** — Can the user open/run this immediately without extra setup? 7. **Overall Verdict** — Ship it / Needs minor fixes / Needs major rework IMPORTANT: If you output improved files, you MUST use this EXACT format (same as the builder): ```filename: path/to/file.ext (complete improved file contents — no truncation, no ellipsis) ``` The label MUST start with `filename:`. Do not output partial files or diffs. If a fix is minor (typo, one-liner), just describe it — don't re-output the whole file. Only re-output files that have real bugs or missing pieces. REQUIRED — end every review with this structured block (no exceptions): ## VERDICT VERDICT: SHIP_IT (Replace SHIP_IT with MINOR_FIXES if only cosmetic/edge-case issues exist, or MAJOR_REWORK if any core feature is broken, missing, or non-functional.) CHECKLIST (score each item against the original request): - UI renders correctly on first load (no blank canvas, no layout breaks): PASS/FAIL - Core feature 1 [name it]: PASS/FAIL - Core feature 2 [name it]: PASS/FAIL - Core feature 3 [name it]: PASS/FAIL - Progressive disclosure (interactive sections hidden until needed): PASS/FAIL - Works immediately without a server / with stated run command: PASS/FAIL Use MAJOR_REWORK if ANY core feature is FAIL. List specific failure reasons so the builder knows exactly what to fix.""", } # ── Provider / model catalogue ──────────────────────────────────────────────── PROVIDER_MODELS = { "groq": ["llama-3.3-70b-versatile", "llama-3.1-70b-versatile", "mixtral-8x7b-32768", "gemma2-9b-it", "llama-3.1-8b-instant"], "anthropic": ["claude-sonnet-4-6", "claude-opus-4-6", "claude-haiku-4-5-20251001"], "nvidia": NVIDIA_CODE_MODELS + NVIDIA_TEXT_MODELS + NVIDIA_VISION_MODELS, "kimi": ["moonshot-v1-128k", "moonshot-v1-32k", "moonshot-v1-8k"], "huggingface": ["Qwen/Qwen2.5-72B-Instruct", "meta-llama/Llama-3.3-70B-Instruct", "mistralai/Mistral-7B-Instruct-v0.3"], "openai": ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo"], } PRESETS = { "🆓 All Groq (Free)": { "strategy": ("groq", "llama-3.3-70b-versatile"), "design": ("groq", "llama-3.3-70b-versatile"), "builder": ("groq", "llama-3.3-70b-versatile"), "reviewer": ("groq", "llama-3.3-70b-versatile"), }, "⚡ Groq Build + Anthropic Review": { "strategy": ("groq", "llama-3.3-70b-versatile"), "design": ("groq", "llama-3.3-70b-versatile"), "builder": ("groq", "llama-3.3-70b-versatile"), "reviewer": ("anthropic", "claude-sonnet-4-6"), }, "🎮 NVIDIA NIM (Auto-select best)": { "strategy": ("nvidia", "meta/llama-3.3-70b-instruct"), "design": ("nvidia", "meta/llama-3.3-70b-instruct"), "builder": ("nvidia", "qwen/qwen2.5-coder-32b-instruct"), "reviewer": ("nvidia", "meta/llama-3.3-70b-instruct"), }, "🌙 Groq Strategy + Kimi Build": { "strategy": ("groq", "llama-3.3-70b-versatile"), "design": ("groq", "llama-3.3-70b-versatile"), "builder": ("kimi", "moonshot-v1-32k"), "reviewer": ("groq", "llama-3.3-70b-versatile"), }, "🏆 All Anthropic (Best Quality)": { "strategy": ("anthropic", "claude-sonnet-4-6"), "design": ("anthropic", "claude-sonnet-4-6"), "builder": ("anthropic", "claude-sonnet-4-6"), "reviewer": ("anthropic", "claude-sonnet-4-6"), }, } # ── Helpers ──────────────────────────────────────────────────────────────── def extract_code_files(text: str) -> list[dict]: """ Parse code blocks that label a filename. Handles multiple formats: ```filename: path/to/file.ext (canonical — enforced in system prompt) ```file: path/to/file.ext ```javascript: src/app.js (language: path style used by some models) ```index.html: path/to/index.html A dot in the captured path is required (ensures it's a file, not a bare language tag). """ pattern = re.compile( r"```(?:filename|file|[\w.+-]+):\s*([\w./\\-]+\.[\w]+)\n(.*?)```", re.DOTALL, ) seen = set() files = [] for m in pattern.finditer(text): fname = m.group(1).strip() if fname not in seen: seen.add(fname) files.append({"filename": fname, "content": m.group(2).rstrip()}) return files def build_zip(contents: dict, code_text: str, review_text: str) -> str: """Create a ZIP with all generated docs and code files. Returns zip path.""" tmpdir = Path(tempfile.mkdtemp()) docs = { "strategy.md": f"# Strategy\n\n{contents.get('strategy', '')}", "design.md": f"# Design Spec\n\n{contents.get('design', '')}", "build_output.md": f"# Build Output\n\n{code_text}", "review.md": f"# Code Review\n\n{review_text}", } for fname, text in docs.items(): (tmpdir / fname).write_text(text, encoding="utf-8") code_dir = tmpdir / "code" code_dir.mkdir() for f in extract_code_files(code_text): dest = code_dir / f["filename"] dest.parent.mkdir(parents=True, exist_ok=True) dest.write_text(f["content"], encoding="utf-8") for f in extract_code_files(review_text): dest = code_dir / f["filename"] dest.parent.mkdir(parents=True, exist_ok=True) dest.write_text(f["content"], encoding="utf-8") zip_path = str(tmpdir / "project.zip") with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: for fpath in tmpdir.rglob("*"): if fpath.is_file() and fpath.name != "project.zip": zf.write(fpath, fpath.relative_to(tmpdir)) return zip_path def static_analysis(html_content: str) -> list: """Zero-dependency static analysis of built HTML/JS for common bugs.""" issues = [] # 1. Canvas elements visible on first load for m in re.finditer(r'