sanelyhusen's picture
Update app.py
950aca0 verified
Raw History Blame Contribute Delete
37.6 kB
"""
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 <head>:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
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'<canvas([^>]*)>', html_content, re.IGNORECASE):
attrs = m.group(1)
if not any(x in attrs for x in ['d-none', 'display:none', 'display: none', 'hidden']):
issues.append(
"Canvas is visible on initial load โ€” should start hidden (d-none) "
"and be revealed by JS only after an image/file is provided"
)
# 2. onclick functions not defined in <script>
script_blocks = re.findall("<script[^>]*>(.*?)</script>", html_content, re.DOTALL | re.IGNORECASE)
script_text = "\n".join(script_blocks)
onclick_funcs = set(re.findall('onclick=["\'](\\w+)\\s*\\(', html_content))
for func in onclick_funcs:
defined = any((kw + " " + func) in script_text for kw in ("function", "const", "let", "var"))
if not defined:
issues.append("onclick calls '" + func + "()' but it is not defined in any <script> block")
# 3. getElementById calls with no matching id in HTML
get_ids = set(re.findall("getElementById\\(['\"]([^'\"]+)['\"]\\)", script_text))
def_ids = set(re.findall("\\bid=['\"]([^'\"]+)['\"]", html_content))
for gid in get_ids:
if gid not in def_ids:
issues.append("getElementById('" + gid + "') called but no element with id='" + gid + "' exists in HTML")
return issues
def make_preview_iframe(b_out: str) -> str | None:
"""Extract the first .html file from build output and wrap in a sandboxed iframe."""
files = extract_code_files(b_out)
html_file = next((f for f in files if f['filename'].lower().endswith('.html')), None)
if not html_file:
return None
escaped = html_file['content'].replace('&', '&amp;').replace('"', '&quot;')
return (
'<div style="border:2px solid #e2e8f0;border-radius:12px;overflow:hidden;margin-top:4px">'
f'<iframe srcdoc="{escaped}" '
'style="width:100%;height:640px;border:none;" '
'sandbox="allow-scripts allow-same-origin allow-forms allow-modals"></iframe>'
'</div>'
)
def set_env_keys(**kwargs):
mapping = {
"groq_key": "GROQ_API_KEY",
"anthropic_key": "ANTHROPIC_API_KEY",
"nvidia_key": "NVIDIA_API_KEY",
"kimi_key": "MOONSHOT_API_KEY",
"hf_token": "HF_TOKEN",
"openai_key": "OPENAI_API_KEY",
}
for kwarg, env_var in mapping.items():
val = kwargs.get(kwarg, "").strip()
if val:
os.environ[env_var] = val
def make_agent_config(name, provider, model, temperature, max_tokens, stage):
return {
"name": name,
"provider": provider,
"model": model,
"temperature": temperature,
"max_tokens": max_tokens,
"system_prompt": SYSTEM_PROMPTS[stage],
}
# โ”€โ”€ Background NVIDIA health check on startup โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def _startup_health_check():
"""Run silently in background so health data is ready when user hits Build."""
key = os.environ.get("NVIDIA_API_KEY", "")
if key:
run_nvidia_health_check(key)
threading.Thread(target=_startup_health_check, daemon=True).start()
# โ”€โ”€ Pipeline โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def run_build_pipeline(
prompt,
ref_image,
groq_key, anthropic_key, nvidia_key, kimi_key, hf_token, openai_key,
s_provider, s_model,
d_provider, d_model,
b_provider, b_model,
r_provider, r_model,
):
"""Generator โ€” yields (status, strategy, design, builder, reviewer, zip, preview) after each stage."""
EMPTY = ("", "", "", "", None, None)
if not prompt.strip():
yield ("\u274c Please enter a prompt first.", *EMPTY)
return
set_env_keys(
groq_key=groq_key, anthropic_key=anthropic_key,
nvidia_key=nvidia_key, kimi_key=kimi_key,
hf_token=hf_token, openai_key=openai_key,
)
image_b64 = _encode_image(ref_image)
image_note = "\n\n*[A reference image has been provided โ€” study it carefully.]*" if image_b64 else ""
strategy_cfg = make_agent_config("Strategy Agent", s_provider, s_model, 0.7, 2048, "strategy")
design_cfg = make_agent_config("Design Agent", d_provider, d_model, 0.6, 2048, "design")
builder_cfg = make_agent_config("Builder Agent", b_provider, b_model, 0.2, 8192, "builder")
reviewer_cfg = make_agent_config("Code Review Agent", r_provider, r_model, 0.4, 4096, "reviewer")
s_out = d_out = b_out = r_out = ""
preview_html = None
# Stage 1 โ€” Strategy
yield (f"\u23f3 **Stage 1/4** โ€” Strategy Agent running\u2026 ({s_provider}/{s_model})", s_out, d_out, b_out, r_out, None, None)
try:
t0 = time.time()
res = run_agent_with_fallback(
strategy_cfg,
f"User's build request:\n\n{prompt}{image_note}\n\nProduce a comprehensive strategy document.",
"strategy", image_b64=image_b64,
)
s_out = res["content"]
yield (
f"\u2705 Strategy done ({res['input_tokens']+res['output_tokens']:,} tok, {round(time.time()-t0,1)}s) "
f"\u2014 used **{res['model']}**\n\u23f3 **Stage 2/4** \u2014 Design Agent running\u2026",
s_out, d_out, b_out, r_out, None, None,
)
except Exception as e:
yield (f"\u274c Strategy Agent failed: {e}", s_out, d_out, b_out, r_out, None, None)
return
# Stage 2 โ€” Design
try:
t0 = time.time()
res = run_agent_with_fallback(
design_cfg,
f"Original request:\n{prompt}{image_note}\n\n--- Strategy ---\n{s_out}\n\nProduce a detailed design spec.",
"design", image_b64=image_b64,
)
d_out = res["content"]
yield (
f"\u2705 Design done ({res['input_tokens']+res['output_tokens']:,} tok, {round(time.time()-t0,1)}s) "
f"\u2014 used **{res['model']}**\n\u23f3 **Stage 3/4** \u2014 Builder Agent running\u2026 *(this takes longest)*",
s_out, d_out, b_out, r_out, None, None,
)
except Exception as e:
yield (f"\u274c Design Agent failed: {e}", s_out, d_out, b_out, r_out, None, None)
return
# Stage 3 โ€” Builder
try:
t0 = time.time()
res = run_agent_with_fallback(
builder_cfg,
(
f"Original request:\n{prompt}\n\n"
f"--- Strategy ---\n{s_out}\n\n"
f"--- Design Spec ---\n{d_out}\n\n"
"Build the complete, working implementation now.\n\n"
"MANDATORY OUTPUT FORMAT for every file:\n"
"```filename: path/to/file.ext\n"
"(complete file contents here)\n"
"```\n\n"
"Rules:\n"
"- Label MUST start with `filename:` (not `file:`, not a language name)\n"
"- For web apps: prefer a SINGLE self-contained index.html with inline CSS+JS\n"
"- For Python: include requirements.txt and README.md with run instructions\n"
"- Zero placeholders. Zero truncation. Fully working on first open/run."
),
"builder",
)
b_out = res["content"]
# Live preview + zero-cost static analysis
preview_html = make_preview_iframe(b_out)
html_files = [f for f in extract_code_files(b_out) if f["filename"].lower().endswith(".html")]
sa_issues = static_analysis(html_files[0]["content"]) if html_files else []
if sa_issues:
sa_note = (
"\n\n\u26a0\ufe0f **Static Analysis โ€” " + str(len(sa_issues)) + " issue(s) found:** "
+ " \u00b7 ".join(sa_issues[:2])
+ ("\u2026" if len(sa_issues) > 2 else "")
)
else:
sa_note = "\n\n\u2705 **Static Analysis:** No structural issues detected"
yield (
f"\u2705 Build done ({res['input_tokens']+res['output_tokens']:,} tok, {round(time.time()-t0,1)}s) "
f"\u2014 used **{res['model']}**{sa_note}\n\u23f3 **Stage 4/4** \u2014 Code Review running\u2026",
s_out, d_out, b_out, r_out, None, preview_html,
)
except Exception as e:
yield (f"\u274c Builder Agent failed: {e}", s_out, d_out, b_out, r_out, None, None)
return
# Stage 4 โ€” Review + self-correcting iteration loop (up to MAX_FIX_ROUNDS)
MAX_FIX_ROUNDS = 2
sa_context = (
"\n\n--- Static Analysis Results (fix these too) ---\n"
+ "\n".join(f"- {i}" for i in sa_issues)
if sa_issues else ""
)
def _run_reviewer(b_text):
return run_agent_with_fallback(
reviewer_cfg,
f"Original request:\n{prompt}\n\n--- Code to Review ---\n{b_text}{sa_context}",
"reviewer",
)
def _verdict(r_text):
if "MAJOR_REWORK" in r_text: return "MAJOR_REWORK"
if "MINOR_FIXES" in r_text: return "MINOR_FIXES"
return "SHIP_IT"
try:
t0 = time.time()
res = _run_reviewer(b_out)
r_out = res["content"]
yield (
f"\u2705 Review done ({res['input_tokens']+res['output_tokens']:,} tok, {round(time.time()-t0,1)}s) "
f"\u2014 verdict: **{_verdict(r_out)}**",
s_out, d_out, b_out, r_out, None, preview_html,
)
except Exception as e:
yield (f"\u274c Code Review Agent failed: {e}", s_out, d_out, b_out, r_out, None, preview_html)
return
for fix_round in range(MAX_FIX_ROUNDS):
if _verdict(r_out) != "MAJOR_REWORK":
break
yield (
f"\U0001f504 **Fix round {fix_round+1}/{MAX_FIX_ROUNDS}** \u2014 Builder re-running with reviewer feedback\u2026",
s_out, d_out, b_out, r_out, None, preview_html,
)
try:
t0 = time.time()
res = run_agent_with_fallback(
builder_cfg,
(
f"ORIGINAL REQUEST:\n{prompt}\n\n"
f"--- Strategy ---\n{s_out}\n\n"
f"--- Design Spec ---\n{d_out}\n\n"
f"--- Your previous build ---\n{b_out}\n\n"
f"--- Code review failures to fix ---\n{r_out}\n\n"
"Fix EVERY item marked FAIL. Output complete corrected files using filename: format. "
"Do not change anything already marked PASS. Zero placeholders. Zero truncation."
),
"builder",
)
b_out = res["content"]
preview_html = make_preview_iframe(b_out) or preview_html
yield (
f"\u2705 Fix round {fix_round+1} done ({res['input_tokens']+res['output_tokens']:,} tok, {round(time.time()-t0,1)}s) "
f"\u2014 used **{res['model']}**\n\U0001f50d Re-reviewing\u2026",
s_out, d_out, b_out, r_out, None, preview_html,
)
except Exception as e:
yield (f"\u274c Fix round {fix_round+1} failed: {e}", s_out, d_out, b_out, r_out, None, preview_html)
break
try:
t0 = time.time()
res = _run_reviewer(b_out)
r_out = res["content"]
yield (
f"\u2705 Re-review done ({res['input_tokens']+res['output_tokens']:,} tok, {round(time.time()-t0,1)}s) "
f"\u2014 verdict: **{_verdict(r_out)}**",
s_out, d_out, b_out, r_out, None, preview_html,
)
except Exception as e:
yield (f"\u274c Re-review failed: {e}", s_out, d_out, b_out, r_out, None, preview_html)
break
# Package
try:
zip_path = build_zip({"strategy": s_out, "design": d_out}, b_out, r_out)
except Exception:
zip_path = None
code_files = {f["filename"] for f in extract_code_files(b_out) + extract_code_files(r_out)}
final_verdict = _verdict(r_out)
verdict_emoji = "\U0001f389" if final_verdict == "SHIP_IT" else "\u26a0\ufe0f" if final_verdict == "MINOR_FIXES" else "\U0001f527"
yield (
f"{verdict_emoji} **Pipeline complete!** {len(code_files)} file(s) generated. "
f"Final verdict: **{final_verdict}**. Click **Download Project** to get your ZIP.",
s_out, d_out, b_out, r_out, zip_path, preview_html,
)
# โ”€โ”€ UI helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def apply_preset(preset_name):
p = PRESETS.get(preset_name, PRESETS["๐Ÿ†“ All Groq (Free)"])
return (
p["strategy"][0], p["strategy"][1],
p["design"][0], p["design"][1],
p["builder"][0], p["builder"][1],
p["reviewer"][0], p["reviewer"][1],
)
def update_model_dropdown(provider):
models = PROVIDER_MODELS.get(provider, [])
default = models[0] if models else ""
return gr.Dropdown(choices=models, value=default)
def do_health_check(nvidia_key_input):
key = nvidia_key_input.strip() or os.environ.get("NVIDIA_API_KEY", "")
if not key:
return "โŒ No NVIDIA API key found. Enter it in the field above or add it as an HF Secret."
if key:
os.environ["NVIDIA_API_KEY"] = key
reset_health_cache()
run_nvidia_health_check(key, force=True)
return get_health_summary()
# โ”€โ”€ UI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
CSS = """
.agent-panel { border-radius: 12px !important; }
.status-box { font-size: 15px; font-weight: 500; }
footer { display: none !important; }
#title-row { text-align: center; margin-bottom: 8px; }
"""
with gr.Blocks(title="๐Ÿค– Multi-Agent Builder") as demo:
gr.Markdown("""
# ๐Ÿค– Multi-Agent Builder
**Strategy โ†’ Design โ†’ Build โ†’ Code Review** โ€” four AI agents, one prompt, complete project.
""", elem_id="title-row")
with gr.Tabs():
# โ”€โ”€ TAB 1: SETTINGS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
with gr.Tab("๐Ÿ”‘ Settings"):
gr.Markdown("### API Keys")
gr.Markdown(
"Keys are stored in your browser session only โ€” never saved to disk. "
"If you've added keys as **HF Space Secrets**, leave those fields blank."
)
with gr.Row():
with gr.Column():
groq_key = gr.Textbox(label="๐ŸŸข Groq API Key (Free tier)", type="password",
placeholder="gsk_...", value=os.environ.get("GROQ_API_KEY", ""))
anthropic_key = gr.Textbox(label="๐ŸŸฃ Anthropic API Key", type="password",
placeholder="sk-ant-...", value=os.environ.get("ANTHROPIC_API_KEY", ""))
openai_key = gr.Textbox(label="โฌ› OpenAI API Key", type="password",
placeholder="sk-...", value=os.environ.get("OPENAI_API_KEY", ""))
with gr.Column():
nvidia_key = gr.Textbox(label="๐ŸŸฉ NVIDIA NIM API Key ($200 free credits)", type="password",
placeholder="nvapi-...", value=os.environ.get("NVIDIA_API_KEY", ""))
kimi_key = gr.Textbox(label="๐ŸŒ™ Kimi / Moonshot API Key", type="password",
placeholder="sk-...", value=os.environ.get("MOONSHOT_API_KEY", ""))
hf_token = gr.Textbox(label="๐Ÿค— HuggingFace Token", type="password",
placeholder="hf_...", value=os.environ.get("HF_TOKEN", ""))
gr.Markdown("---")
# NVIDIA Health Check section
gr.Markdown("### ๐ŸŽฎ NVIDIA Model Health Check")
gr.Markdown(
"Click below to ping all NVIDIA NIM models and find out which ones are currently "
"responding. The pipeline will automatically use healthy models and fall back gracefully."
)
health_btn = gr.Button("๐Ÿ” Check NVIDIA Models", variant="secondary")
health_md = gr.Markdown("*Click above to run the health check.*")
health_btn.click(fn=do_health_check, inputs=[nvidia_key], outputs=[health_md])
gr.Markdown("---")
gr.Markdown("### Agent Configuration")
gr.Markdown("Select a preset to configure all agents at once, or set each agent individually below.")
with gr.Row():
preset_dd = gr.Dropdown(choices=list(PRESETS.keys()), value="๐Ÿ†“ All Groq (Free)",
label="Quick Preset", scale=2)
apply_btn = gr.Button("Apply Preset โ†’", scale=1, variant="secondary")
gr.Markdown("#### Per-Agent Settings")
agent_rows = {}
for stage, label, icon in [
("strategy", "Strategy Agent", "๐Ÿง "),
("design", "Design Agent", "๐ŸŽจ"),
("builder", "Builder Agent", "๐Ÿ”จ"),
("reviewer", "Code Review Agent", "๐Ÿ”"),
]:
with gr.Group():
gr.Markdown(f"**{icon} {label}**")
with gr.Row():
prov = gr.Dropdown(choices=list(PROVIDER_MODELS.keys()), value="groq",
label="Provider", scale=1)
mod = gr.Dropdown(choices=PROVIDER_MODELS["groq"],
value="llama-3.3-70b-versatile",
label="Model", scale=2)
prov.change(fn=update_model_dropdown, inputs=prov, outputs=mod)
agent_rows[stage] = (prov, mod)
s_provider, s_model = agent_rows["strategy"]
d_provider, d_model = agent_rows["design"]
b_provider, b_model = agent_rows["builder"]
r_provider, r_model = agent_rows["reviewer"]
apply_btn.click(
fn=apply_preset,
inputs=[preset_dd],
outputs=[s_provider, s_model, d_provider, d_model,
b_provider, b_model, r_provider, r_model],
)
# โ”€โ”€ TAB 2: BUILD โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
with gr.Tab("๐Ÿš€ Build"):
with gr.Row():
with gr.Column(scale=3):
prompt_input = gr.Textbox(
label="What do you want to build?",
placeholder=(
"Examples:\n"
"โ€ข Build me a Pomodoro timer web app with local storage\n"
"โ€ข Create a Python CLI tool that resizes images in a folder\n"
"โ€ข Build a REST API for a simple blog with FastAPI\n"
"โ€ข Make a todo app with drag-and-drop and dark mode"
),
lines=5,
)
# Reference image upload
ref_image = gr.Image(
label="๐Ÿ“Ž Reference Image (optional) โ€” upload a mockup, screenshot, or diagram for agents to study",
type="pil",
sources=["upload"],
)
build_btn = gr.Button("๐Ÿš€ Build It", variant="primary", size="lg")
with gr.Column(scale=2):
gr.Markdown("### Pipeline Stages")
gr.Markdown("""
| Stage | Agent | What it does |
|-------|-------|--------------|
| 1 | ๐Ÿง  Strategy | Goals, scope, tech stack |
| 2 | ๐ŸŽจ Design | Architecture, file tree, data models |
| 3 | ๐Ÿ”จ Builder | Complete, working code |
| 4 | ๐Ÿ” Reviewer | Bug hunt + improvements |
**๐Ÿ’ก Reference Image**
Upload a mockup, screenshot, or diagram and the Strategy + Design agents will study it.
Vision-capable models: Anthropic Claude, NVIDIA llama-3.2-vision, GPT-4o.
""")
status_md = gr.Markdown(
value="*Enter a prompt and click Build It to start.*",
elem_classes=["status-box"],
)
with gr.Row():
download_file = gr.File(label="๐Ÿ“ฆ Download Project (ZIP)", visible=True, scale=1)
gr.Markdown("### ๐Ÿ“ธ Live Preview")
gr.Markdown("*The built app renders below โ€” interact with it directly in the browser.*")
preview_out = gr.HTML(
value="<p style='color:#94a3b8;font-style:italic;padding:16px'>Preview will appear here after build completes.</p>",
)
gr.Markdown("---")
gr.Markdown("### Agent Outputs")
with gr.Accordion("๐Ÿง  Strategy", open=False, elem_classes=["agent-panel"]):
strategy_md = gr.Markdown("*Not run yet.*")
with gr.Accordion("๐ŸŽจ Design Spec", open=False, elem_classes=["agent-panel"]):
design_md = gr.Markdown("*Not run yet.*")
with gr.Accordion("๐Ÿ”จ Build Output", open=False, elem_classes=["agent-panel"]):
builder_md = gr.Markdown("*Not run yet.*")
with gr.Accordion("๐Ÿ” Code Review", open=False, elem_classes=["agent-panel"]):
reviewer_md = gr.Markdown("*Not run yet.*")
build_btn.click(
fn=run_build_pipeline,
inputs=[
prompt_input, ref_image,
groq_key, anthropic_key, nvidia_key, kimi_key, hf_token, openai_key,
s_provider, s_model,
d_provider, d_model,
b_provider, b_model,
r_provider, r_model,
],
outputs=[status_md, strategy_md, design_md, builder_md, reviewer_md, download_file, preview_out],
)
# โ”€โ”€ TAB 3: GUIDE โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
with gr.Tab("๐Ÿ“– Guide"):
gr.Markdown("""
## Getting Started
### 1. Get a Free API Key (Groq โ€” easiest)
1. Go to [console.groq.com](https://console.groq.com) and sign up
2. Create an API key and paste it in **๐Ÿ”‘ Settings โ†’ Groq API Key**
3. The **๐Ÿ†“ All Groq (Free)** preset is already selected โ€” you're ready
### 2. Use NVIDIA NIM (Free $200 credits, best for coding)
1. Go to [build.nvidia.com](https://build.nvidia.com) and sign up
2. Click **Get API Key** to generate your key
3. Paste it in **๐Ÿ”‘ Settings โ†’ NVIDIA NIM API Key**
4. Click **๐Ÿ” Check NVIDIA Models** to see which models are live right now
5. Select the **๐ŸŽฎ NVIDIA NIM** preset โ€” the pipeline auto-picks the best available model
### 3. Upload a Reference Image
- In the **๐Ÿš€ Build** tab, upload a mockup, screenshot, or diagram
- The Strategy and Design agents will study it alongside your text prompt
- Works best with vision-capable models: Anthropic Claude, NVIDIA llama-3.2-vision, GPT-4o
### 4. Build your first project
1. Go to the **๐Ÿš€ Build** tab
2. Type what you want (be specific โ€” more detail = better output)
3. Optionally upload a reference image
4. Click **Build It** and watch the 4 agents run
5. Download the ZIP โ€” open `code/index.html` (or run the Python file) directly
---
## Provider Guide
| Provider | Free Tier | Best For |
|----------|-----------|----------|
| **Groq** | 14k req/day | Everything โ€” fastest inference |
| **NVIDIA NIM** | $200 credits on signup | Coding (Qwen2.5-Coder), vision |
| **Anthropic** | Paid (best quality) | Strategy + Review + vision |
| **Kimi** | Credits on signup | Long-context builds |
| **HuggingFace** | Rate-limited | Experimenting |
## Prompt Tips
- โœ… **Be specific**: "Build a Pomodoro timer web app with dark mode, sound alerts, and local storage for stats"
- โœ… **Name your stack**: "Using FastAPI and PostgreSQL, build a REST API for a blog"
- โœ… **Upload a reference**: attach a screenshot so agents can see exactly what you mean
- โŒ **Too vague**: "Build an app" โ†’ agents will make assumptions that may not match what you want
""")
gr.Markdown(
"<center><sub>Multi-Agent Builder ยท Built with Gradio ยท "
"Powered by your choice of AI provider</sub></center>"
)
if __name__ == "__main__":
demo.launch(
theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="purple"),
css=CSS,
)