sanelyhusen commited on
Commit
f56147a
ยท
verified ยท
1 Parent(s): 5cd48c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -170
app.py CHANGED
@@ -1,25 +1,31 @@
1
  """
2
  Multi-Agent Builder โ€” HuggingFace Spaces / Gradio App
3
  =====================================================
4
- A web platform that turns a single prompt into a complete project
5
- using four specialized AI agents running in sequence:
6
-
7
- Strategy โ†’ Design โ†’ Builder โ†’ Code Review
8
-
9
- Supports Groq (free), Anthropic, NVIDIA NIM, Kimi, HuggingFace, and more.
10
- API keys can be provided in the UI or pre-set as HF Space Secrets.
 
11
  """
12
 
13
  import gradio as gr
14
  import os
15
  import re
16
- import json
17
  import zipfile
18
  import tempfile
19
  import time
 
20
  from pathlib import Path
21
 
22
- from agents import run_agent, PROVIDER_DEFAULTS
 
 
 
 
 
23
 
24
 
25
  # โ”€โ”€ System prompts โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -37,7 +43,8 @@ Your output must include:
37
  6. **Success Criteria** โ€” How do we know this is done and working?
38
 
39
  Be direct and opinionated. Don't hedge excessively. Make decisions.
40
- Format with clear markdown headers and bullet points.""",
 
41
 
42
  "design": """You are a senior UX designer and software architect.
43
  You receive a strategy document and translate it into a concrete technical design spec.
@@ -52,24 +59,26 @@ Your output must include:
52
  7. **Edge Cases to Handle** โ€” At least 3 edge cases the builder must account for
53
 
54
  Be precise. Give the builder everything they need to start coding immediately.
55
- Format with clear markdown headers. Use code blocks for schemas and file trees.""",
 
56
 
57
  "builder": """You are an expert full-stack developer. You write clean, production-quality code.
58
  You receive a strategy document and a design spec, and you build the thing.
59
 
60
- Rules:
61
  - Write COMPLETE, WORKING code. No placeholders, no "TODO" stubs.
62
- - Output each file in a clearly labelled code block using this exact format:
63
 
64
  ```filename: path/to/file.ext
65
  [file contents here]
66
  ```
67
 
68
- - Include ALL files needed to run the project (entry point, helpers, config, etc.)
69
- - Add inline comments for non-obvious logic
70
- - Handle the edge cases specified in the design document
71
- - If building a web app: make it look clean and professional (not bare HTML)
72
- - If building a Python script: include a __main__ guard and clear CLI usage
 
73
 
74
  Do not truncate files. Write them completely.""",
75
 
@@ -85,7 +94,7 @@ Your review must cover:
85
  6. **Overall Verdict** โ€” Ship it / Needs minor fixes / Needs major rework
86
 
87
  After the review, output improved versions of any files that have significant issues,
88
- using the same format as the builder:
89
 
90
  ```filename: path/to/file.ext
91
  [improved file contents]
@@ -99,7 +108,7 @@ If the code is solid, say so clearly and don't make changes for the sake of it."
99
  PROVIDER_MODELS = {
100
  "groq": ["llama-3.3-70b-versatile", "llama-3.1-70b-versatile", "mixtral-8x7b-32768", "gemma2-9b-it", "llama-3.1-8b-instant"],
101
  "anthropic": ["claude-sonnet-4-6", "claude-opus-4-6", "claude-haiku-4-5-20251001"],
102
- "nvidia": ["meta/llama-3.3-70b-instruct", "qwen/qwen2.5-coder-32b-instruct", "mistralai/mixtral-8x7b-instruct-v0.1", "nvidia/llama-3.1-nemotron-70b-instruct"],
103
  "kimi": ["moonshot-v1-128k", "moonshot-v1-32k", "moonshot-v1-8k"],
104
  "huggingface": ["Qwen/Qwen2.5-72B-Instruct", "meta-llama/Llama-3.3-70B-Instruct", "mistralai/Mistral-7B-Instruct-v0.3"],
105
  "openai": ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo"],
@@ -118,6 +127,12 @@ PRESETS = {
118
  "builder": ("groq", "llama-3.3-70b-versatile"),
119
  "reviewer": ("anthropic", "claude-sonnet-4-6"),
120
  },
 
 
 
 
 
 
121
  "๐ŸŒ™ Groq Strategy + Kimi Build": {
122
  "strategy": ("groq", "llama-3.3-70b-versatile"),
123
  "design": ("groq", "llama-3.3-70b-versatile"),
@@ -130,65 +145,66 @@ PRESETS = {
130
  "builder": ("anthropic", "claude-sonnet-4-6"),
131
  "reviewer": ("anthropic", "claude-sonnet-4-6"),
132
  },
133
- "๐ŸŽฎ NVIDIA NIM (Free Credits)": {
134
- "strategy": ("nvidia", "meta/llama-3.3-70b-instruct"),
135
- "design": ("nvidia", "meta/llama-3.3-70b-instruct"),
136
- "builder": ("nvidia", "qwen/qwen2.5-coder-32b-instruct"),
137
- "reviewer": ("nvidia", "meta/llama-3.3-70b-instruct"),
138
- },
139
  }
140
 
141
  # โ”€โ”€ Helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
142
 
143
  def extract_code_files(text: str) -> list[dict]:
144
- """Parse ```filename: path/to/file``` blocks from agent output."""
145
- pattern = re.compile(r"```(?:filename|file):\s*(.+?)\n(.*?)```", re.DOTALL)
146
- return [
147
- {"filename": m.group(1).strip(), "content": m.group(2).rstrip()}
148
- for m in pattern.finditer(text)
149
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
 
152
  def build_zip(contents: dict, code_text: str, review_text: str) -> str:
153
- """Create a zip file with all generated files and docs. Returns zip path."""
154
  tmpdir = Path(tempfile.mkdtemp())
155
 
156
- # Write markdown docs
157
  docs = {
158
- "strategy.md": f"# Strategy\n\n{contents.get('strategy', '')}",
159
- "design.md": f"# Design Spec\n\n{contents.get('design', '')}",
160
  "build_output.md": f"# Build Output\n\n{code_text}",
161
- "review.md": f"# Code Review\n\n{review_text}",
162
  }
163
  for fname, text in docs.items():
164
  (tmpdir / fname).write_text(text, encoding="utf-8")
165
 
166
- # Write code files
167
  code_dir = tmpdir / "code"
168
  code_dir.mkdir()
169
  for f in extract_code_files(code_text):
170
  dest = code_dir / f["filename"]
171
  dest.parent.mkdir(parents=True, exist_ok=True)
172
  dest.write_text(f["content"], encoding="utf-8")
173
-
174
- # Apply reviewer patches (overwrite with improved files)
175
  for f in extract_code_files(review_text):
176
  dest = code_dir / f["filename"]
177
  dest.parent.mkdir(parents=True, exist_ok=True)
178
  dest.write_text(f["content"], encoding="utf-8")
179
 
180
- # Zip everything
181
  zip_path = str(tmpdir / "project.zip")
182
  with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
183
  for fpath in tmpdir.rglob("*"):
184
  if fpath.is_file() and fpath.name != "project.zip":
185
  zf.write(fpath, fpath.relative_to(tmpdir))
186
-
187
  return zip_path
188
 
189
 
190
  def set_env_keys(**kwargs):
191
- """Push non-empty UI key inputs into os.environ."""
192
  mapping = {
193
  "groq_key": "GROQ_API_KEY",
194
  "anthropic_key": "ANTHROPIC_API_KEY",
@@ -205,150 +221,154 @@ def set_env_keys(**kwargs):
205
 
206
  def make_agent_config(name, provider, model, temperature, max_tokens, stage):
207
  return {
208
- "name": name,
209
- "provider": provider,
210
- "model": model,
211
- "temperature": temperature,
212
- "max_tokens": max_tokens,
213
  "system_prompt": SYSTEM_PROMPTS[stage],
214
  }
215
 
216
 
217
- # โ”€โ”€ Pipeline (generator for streaming UI updates) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
 
 
 
 
 
 
 
 
 
218
 
219
  def run_build_pipeline(
220
  prompt,
 
221
  groq_key, anthropic_key, nvidia_key, kimi_key, hf_token, openai_key,
222
  s_provider, s_model,
223
  d_provider, d_model,
224
  b_provider, b_model,
225
  r_provider, r_model,
226
  ):
227
- """
228
- Generator that yields (status, strategy_md, design_md, builder_md, reviewer_md, zip_file)
229
- after each agent completes, enabling streaming UI updates.
230
- """
231
  EMPTY = ("", "", "", "", None)
232
 
233
  if not prompt.strip():
234
  yield ("โŒ Please enter a prompt first.", *EMPTY)
235
  return
236
 
237
- # Push API keys into environment
238
  set_env_keys(
239
  groq_key=groq_key, anthropic_key=anthropic_key,
240
  nvidia_key=nvidia_key, kimi_key=kimi_key,
241
  hf_token=hf_token, openai_key=openai_key,
242
  )
243
 
244
- # Build agent configs from UI choices
245
- strategy_cfg = make_agent_config("Strategy Agent", s_provider, s_model, 0.7, 2048, "strategy")
246
- design_cfg = make_agent_config("Design Agent", d_provider, d_model, 0.6, 2048, "design")
247
- builder_cfg = make_agent_config("Builder Agent", b_provider, b_model, 0.2, 8192, "builder")
 
 
 
248
  reviewer_cfg = make_agent_config("Code Review Agent", r_provider, r_model, 0.4, 4096, "reviewer")
249
 
250
  s_out = d_out = b_out = r_out = ""
251
 
252
- # โ”€โ”€ Stage 1: Strategy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
253
- yield ("โณ **Stage 1/4** โ€” Strategy Agent runningโ€ฆ", s_out, d_out, b_out, r_out, None)
254
  try:
255
  t0 = time.time()
256
- s_result = run_agent(
257
- strategy_cfg, None,
258
- f"User's build request:\n\n{prompt}\n\nProduce a comprehensive strategy document.",
259
- "strategy", verbose=False,
260
  )
261
- s_out = s_result["content"]
262
- elapsed = round(time.time() - t0, 1)
263
  yield (
264
- f"โœ… Strategy done ({s_result['input_tokens']+s_result['output_tokens']:,} tokens, {elapsed}s)\n"
265
- f"โณ **Stage 2/4** โ€” Design Agent runningโ€ฆ",
266
  s_out, d_out, b_out, r_out, None,
267
  )
268
  except Exception as e:
269
  yield (f"โŒ Strategy Agent failed: {e}", s_out, d_out, b_out, r_out, None)
270
  return
271
 
272
- # โ”€โ”€ Stage 2: Design โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
273
  try:
274
  t0 = time.time()
275
- d_result = run_agent(
276
- design_cfg, None,
277
- f"Original request:\n{prompt}\n\n--- Strategy ---\n{s_out}\n\nProduce a detailed design spec.",
278
- "design", verbose=False,
279
  )
280
- d_out = d_result["content"]
281
- elapsed = round(time.time() - t0, 1)
282
  yield (
283
- f"โœ… Design done ({d_result['input_tokens']+d_result['output_tokens']:,} tokens, {elapsed}s)\n"
284
- f"โณ **Stage 3/4** โ€” Builder Agent runningโ€ฆ *(this takes the longest)*",
285
  s_out, d_out, b_out, r_out, None,
286
  )
287
  except Exception as e:
288
  yield (f"โŒ Design Agent failed: {e}", s_out, d_out, b_out, r_out, None)
289
  return
290
 
291
- # โ”€โ”€ Stage 3: Builder โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
292
  try:
293
  t0 = time.time()
294
- b_result = run_agent(
295
- builder_cfg, None,
296
  (
297
  f"Original request:\n{prompt}\n\n"
298
  f"--- Strategy ---\n{s_out}\n\n"
299
  f"--- Design Spec ---\n{d_out}\n\n"
300
  "Build the complete, working implementation now. "
301
- "Output every file using the ```filename: path/to/file format."
 
302
  ),
303
- "builder", verbose=False,
304
  )
305
- b_out = b_result["content"]
306
- elapsed = round(time.time() - t0, 1)
307
  yield (
308
- f"โœ… Build done ({b_result['input_tokens']+b_result['output_tokens']:,} tokens, {elapsed}s)\n"
309
- f"โณ **Stage 4/4** โ€” Code Review Agent runningโ€ฆ",
310
  s_out, d_out, b_out, r_out, None,
311
  )
312
  except Exception as e:
313
  yield (f"โŒ Builder Agent failed: {e}", s_out, d_out, b_out, r_out, None)
314
  return
315
 
316
- # โ”€โ”€ Stage 4: Reviewer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
317
  try:
318
  t0 = time.time()
319
- r_result = run_agent(
320
- reviewer_cfg, None,
321
  f"Original request:\n{prompt}\n\n--- Code to Review ---\n{b_out}",
322
- "reviewer", verbose=False,
323
  )
324
- r_out = r_result["content"]
325
- elapsed = round(time.time() - t0, 1)
326
  except Exception as e:
327
  yield (f"โŒ Code Review Agent failed: {e}", s_out, d_out, b_out, r_out, None)
328
  return
329
 
330
- # โ”€โ”€ Package project โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
331
  try:
332
- zip_path = build_zip(
333
- {"strategy": s_out, "design": d_out},
334
- b_out, r_out,
335
- )
336
- except Exception as e:
337
  zip_path = None
338
 
339
- code_files = extract_code_files(b_out) + extract_code_files(r_out)
340
- file_count = len({f["filename"] for f in code_files})
341
 
342
  yield (
343
- f"๐ŸŽ‰ **Pipeline complete!** {file_count} file(s) generated. Click **Download Project** to get your code.",
 
344
  s_out, d_out, b_out, r_out, zip_path,
345
  )
346
 
347
 
348
- # โ”€โ”€ Preset handler โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
349
 
350
  def apply_preset(preset_name):
351
- """Return provider+model values for all 4 agents from the selected preset."""
352
  p = PRESETS.get(preset_name, PRESETS["๐Ÿ†“ All Groq (Free)"])
353
  return (
354
  p["strategy"][0], p["strategy"][1],
@@ -359,20 +379,29 @@ def apply_preset(preset_name):
359
 
360
 
361
  def update_model_dropdown(provider):
362
- """Return updated model dropdown choices when provider changes."""
363
  models = PROVIDER_MODELS.get(provider, [])
364
  default = models[0] if models else ""
365
  return gr.Dropdown(choices=models, value=default)
366
 
367
 
 
 
 
 
 
 
 
 
 
 
 
368
  # โ”€โ”€ UI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
369
 
370
  CSS = """
371
  .agent-panel { border-radius: 12px !important; }
372
- .status-box { font-size: 15px; font-weight: 500; }
373
- .gr-button-primary { font-size: 16px !important; }
374
- footer { display: none !important; }
375
- #title-row { text-align: center; margin-bottom: 8px; }
376
  """
377
 
378
  with gr.Blocks(
@@ -381,7 +410,6 @@ with gr.Blocks(
381
  css=CSS,
382
  ) as demo:
383
 
384
- # โ”€โ”€ Header โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
385
  gr.Markdown("""
386
  # ๐Ÿค– Multi-Agent Builder
387
  **Strategy โ†’ Design โ†’ Build โ†’ Code Review** โ€” four AI agents, one prompt, complete project.
@@ -391,11 +419,11 @@ with gr.Blocks(
391
 
392
  # โ”€โ”€ TAB 1: SETTINGS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
393
  with gr.Tab("๐Ÿ”‘ Settings"):
394
- gr.Markdown("""
395
- ### API Keys
396
- Enter keys for the providers you want to use. Keys are stored in your browser session only โ€” never saved to disk.
397
- If you've added keys as **HF Space Secrets**, leave those fields blank (they'll be used automatically).
398
- """)
399
  with gr.Row():
400
  with gr.Column():
401
  groq_key = gr.Textbox(label="๐ŸŸข Groq API Key (Free tier)", type="password",
@@ -412,17 +440,26 @@ If you've added keys as **HF Space Secrets**, leave those fields blank (they'll
412
  hf_token = gr.Textbox(label="๐Ÿค— HuggingFace Token", type="password",
413
  placeholder="hf_...", value=os.environ.get("HF_TOKEN", ""))
414
 
 
 
 
 
 
 
 
 
 
 
 
 
415
  gr.Markdown("---")
416
  gr.Markdown("### Agent Configuration")
417
  gr.Markdown("Select a preset to configure all agents at once, or set each agent individually below.")
418
 
419
- preset_dd = gr.Dropdown(
420
- choices=list(PRESETS.keys()),
421
- value="๐Ÿ†“ All Groq (Free)",
422
- label="Quick Preset",
423
- scale=2,
424
- )
425
- apply_btn = gr.Button("Apply Preset โ†’", scale=1, variant="secondary")
426
 
427
  gr.Markdown("#### Per-Agent Settings")
428
 
@@ -436,18 +473,11 @@ If you've added keys as **HF Space Secrets**, leave those fields blank (they'll
436
  with gr.Group():
437
  gr.Markdown(f"**{icon} {label}**")
438
  with gr.Row():
439
- prov = gr.Dropdown(
440
- choices=list(PROVIDER_MODELS.keys()),
441
- value="groq",
442
- label="Provider",
443
- scale=1,
444
- )
445
- mod = gr.Dropdown(
446
- choices=PROVIDER_MODELS["groq"],
447
- value="llama-3.3-70b-versatile",
448
- label="Model",
449
- scale=2,
450
- )
451
  prov.change(fn=update_model_dropdown, inputs=prov, outputs=mod)
452
  agent_rows[stage] = (prov, mod)
453
 
@@ -459,7 +489,8 @@ If you've added keys as **HF Space Secrets**, leave those fields blank (they'll
459
  apply_btn.click(
460
  fn=apply_preset,
461
  inputs=[preset_dd],
462
- outputs=[s_provider, s_model, d_provider, d_model, b_provider, b_model, r_provider, r_model],
 
463
  )
464
 
465
  # โ”€โ”€ TAB 2: BUILD โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
@@ -477,6 +508,14 @@ If you've added keys as **HF Space Secrets**, leave those fields blank (they'll
477
  ),
478
  lines=5,
479
  )
 
 
 
 
 
 
 
 
480
  build_btn = gr.Button("๐Ÿš€ Build It", variant="primary", size="lg")
481
 
482
  with gr.Column(scale=2):
@@ -488,6 +527,10 @@ If you've added keys as **HF Space Secrets**, leave those fields blank (they'll
488
  | 2 | ๐ŸŽจ Design | Architecture, file tree, data models |
489
  | 3 | ๐Ÿ”จ Builder | Complete, working code |
490
  | 4 | ๐Ÿ” Reviewer | Bug hunt + improvements |
 
 
 
 
491
  """)
492
 
493
  status_md = gr.Markdown(
@@ -503,21 +546,17 @@ If you've added keys as **HF Space Secrets**, leave those fields blank (they'll
503
 
504
  with gr.Accordion("๐Ÿง  Strategy", open=False, elem_classes=["agent-panel"]):
505
  strategy_md = gr.Markdown("*Not run yet.*")
506
-
507
  with gr.Accordion("๐ŸŽจ Design Spec", open=False, elem_classes=["agent-panel"]):
508
  design_md = gr.Markdown("*Not run yet.*")
509
-
510
  with gr.Accordion("๐Ÿ”จ Build Output", open=False, elem_classes=["agent-panel"]):
511
  builder_md = gr.Markdown("*Not run yet.*")
512
-
513
  with gr.Accordion("๐Ÿ” Code Review", open=False, elem_classes=["agent-panel"]):
514
  reviewer_md = gr.Markdown("*Not run yet.*")
515
 
516
- # Wire up the build button
517
  build_btn.click(
518
  fn=run_build_pipeline,
519
  inputs=[
520
- prompt_input,
521
  groq_key, anthropic_key, nvidia_key, kimi_key, hf_token, openai_key,
522
  s_provider, s_model,
523
  d_provider, d_model,
@@ -532,50 +571,53 @@ If you've added keys as **HF Space Secrets**, leave those fields blank (they'll
532
  gr.Markdown("""
533
  ## Getting Started
534
 
535
- ### 1. Get a Free API Key (Groq โ€” recommended)
536
  1. Go to [console.groq.com](https://console.groq.com) and sign up
537
- 2. Create an API key
538
- 3. Paste it in the **๐Ÿ”‘ Settings** tab under *Groq API Key*
539
- 4. The **๐Ÿ†“ All Groq (Free)** preset is already selected โ€” you're ready to go
540
-
541
- ### 2. Build your first project
 
 
 
 
 
 
 
 
 
 
 
542
  1. Go to the **๐Ÿš€ Build** tab
543
- 2. Type what you want to build (be as specific as possible โ€” the more detail, the better the output)
544
- 3. Click **Build It**
545
- 4. Watch the 4 agents run in sequence (Strategy โ†’ Design โ†’ Build โ†’ Review)
546
- 5. Download the ZIP when done
547
-
548
- ### 3. Mix providers for better results
549
- - For the **Builder** agent, models with more output tokens produce more complete code
550
- - Kimi `moonshot-v1-128k` and NVIDIA `qwen2.5-coder-32b` are excellent free/cheap coding models
551
- - Keep a strong model (Groq Llama 70B or Anthropic) on **Strategy** and **Review** โ€” those require real reasoning
552
 
553
  ---
554
 
555
- ## Provider Sign-up Links
556
- | Provider | Free Tier | Best For | Sign-up |
557
- |----------|-----------|----------|---------|
558
- | **Groq** | Generous (14k req/day) | Everything โ€” fastest inference | [console.groq.com](https://console.groq.com) |
559
- | **NVIDIA NIM** | $200 credits on signup | Coding (Qwen2.5-Coder) | [build.nvidia.com](https://build.nvidia.com) |
560
- | **HuggingFace** | Rate-limited free tier | Experimenting | [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) |
561
- | **Kimi** | Credits on signup | Long-context builds | [platform.moonshot.cn](https://platform.moonshot.cn) |
562
- | **Anthropic** | Paid (best quality) | Strategy + Review | [console.anthropic.com](https://console.anthropic.com) |
563
-
564
- ---
565
 
566
  ## Prompt Tips
567
- - โœ… **Be specific**: "Build a Pomodoro timer web app with dark mode, sound alerts, and local storage for stats" โ†’ great output
568
  - โœ… **Name your stack**: "Using FastAPI and PostgreSQL, build a REST API for a blog"
569
- - โœ… **State constraints**: "Must work with no external dependencies" or "Use only the standard library"
570
- - โŒ **Too vague**: "Build an app" โ†’ the agents will make assumptions that may not match what you want
571
  """)
572
 
573
  gr.Markdown(
574
- "<center><sub>Multi-Agent Builder ยท Built with Gradio ยท Powered by your choice of AI provider</sub></center>"
 
575
  )
576
 
577
 
578
- # โ”€โ”€ Launch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
579
-
580
  if __name__ == "__main__":
581
  demo.launch()
 
1
  """
2
  Multi-Agent Builder โ€” HuggingFace Spaces / Gradio App
3
  =====================================================
4
+ Strategy โ†’ Design โ†’ Build โ†’ Code Review
5
+
6
+ New in this version:
7
+ โ€ข NVIDIA NIM with automatic multi-model health checking and fallback
8
+ โ€ข Image reference upload โ€” attach a screenshot/mockup for the agents to study
9
+ โ€ข Vision support for Anthropic Claude and NVIDIA vision models
10
+ โ€ข Fixed code-block filename extraction (handles all model output styles)
11
+ โ€ข Background NVIDIA health check on startup
12
  """
13
 
14
  import gradio as gr
15
  import os
16
  import re
 
17
  import zipfile
18
  import tempfile
19
  import time
20
+ import threading
21
  from pathlib import Path
22
 
23
+ from agents import (
24
+ run_agent, run_agent_with_fallback, _encode_image,
25
+ PROVIDER_DEFAULTS, NVIDIA_TEXT_MODELS, NVIDIA_CODE_MODELS, NVIDIA_VISION_MODELS,
26
+ run_nvidia_health_check, reset_health_cache, get_health_summary,
27
+ get_best_nvidia_model,
28
+ )
29
 
30
 
31
  # โ”€โ”€ System prompts โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
43
  6. **Success Criteria** โ€” How do we know this is done and working?
44
 
45
  Be direct and opinionated. Don't hedge excessively. Make decisions.
46
+ Format with clear markdown headers and bullet points.
47
+ If a reference image is provided, analyse it carefully and incorporate relevant details into your strategy.""",
48
 
49
  "design": """You are a senior UX designer and software architect.
50
  You receive a strategy document and translate it into a concrete technical design spec.
 
59
  7. **Edge Cases to Handle** โ€” At least 3 edge cases the builder must account for
60
 
61
  Be precise. Give the builder everything they need to start coding immediately.
62
+ Format with clear markdown headers. Use code blocks for schemas and file trees.
63
+ If a reference image is provided, describe its layout and incorporate it into the design spec.""",
64
 
65
  "builder": """You are an expert full-stack developer. You write clean, production-quality code.
66
  You receive a strategy document and a design spec, and you build the thing.
67
 
68
+ CRITICAL RULES:
69
  - Write COMPLETE, WORKING code. No placeholders, no "TODO" stubs.
70
+ - Output EVERY file using this EXACT format (required for ZIP packaging):
71
 
72
  ```filename: path/to/file.ext
73
  [file contents here]
74
  ```
75
 
76
+ - The label MUST start with exactly `filename:` followed by a space and the file path.
77
+ - Include ALL files needed to run the project.
78
+ - Add inline comments for non-obvious logic.
79
+ - Handle the edge cases from the design document.
80
+ - If building a web app: make it look clean and professional (not bare HTML).
81
+ - If building a Python script: include a __main__ guard and clear CLI usage.
82
 
83
  Do not truncate files. Write them completely.""",
84
 
 
94
  6. **Overall Verdict** โ€” Ship it / Needs minor fixes / Needs major rework
95
 
96
  After the review, output improved versions of any files that have significant issues,
97
+ using the same exact format as the builder:
98
 
99
  ```filename: path/to/file.ext
100
  [improved file contents]
 
108
  PROVIDER_MODELS = {
109
  "groq": ["llama-3.3-70b-versatile", "llama-3.1-70b-versatile", "mixtral-8x7b-32768", "gemma2-9b-it", "llama-3.1-8b-instant"],
110
  "anthropic": ["claude-sonnet-4-6", "claude-opus-4-6", "claude-haiku-4-5-20251001"],
111
+ "nvidia": NVIDIA_CODE_MODELS + NVIDIA_TEXT_MODELS + NVIDIA_VISION_MODELS,
112
  "kimi": ["moonshot-v1-128k", "moonshot-v1-32k", "moonshot-v1-8k"],
113
  "huggingface": ["Qwen/Qwen2.5-72B-Instruct", "meta-llama/Llama-3.3-70B-Instruct", "mistralai/Mistral-7B-Instruct-v0.3"],
114
  "openai": ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo"],
 
127
  "builder": ("groq", "llama-3.3-70b-versatile"),
128
  "reviewer": ("anthropic", "claude-sonnet-4-6"),
129
  },
130
+ "๐ŸŽฎ NVIDIA NIM (Auto-select best)": {
131
+ "strategy": ("nvidia", "meta/llama-3.3-70b-instruct"),
132
+ "design": ("nvidia", "meta/llama-3.3-70b-instruct"),
133
+ "builder": ("nvidia", "qwen/qwen2.5-coder-32b-instruct"),
134
+ "reviewer": ("nvidia", "meta/llama-3.3-70b-instruct"),
135
+ },
136
  "๐ŸŒ™ Groq Strategy + Kimi Build": {
137
  "strategy": ("groq", "llama-3.3-70b-versatile"),
138
  "design": ("groq", "llama-3.3-70b-versatile"),
 
145
  "builder": ("anthropic", "claude-sonnet-4-6"),
146
  "reviewer": ("anthropic", "claude-sonnet-4-6"),
147
  },
 
 
 
 
 
 
148
  }
149
 
150
  # โ”€โ”€ Helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
151
 
152
  def extract_code_files(text: str) -> list[dict]:
153
+ """
154
+ Parse code blocks that label a filename. Handles multiple formats:
155
+ ```filename: path/to/file.ext (canonical โ€” enforced in system prompt)
156
+ ```file: path/to/file.ext
157
+ ```javascript: src/app.js (language: path style used by some models)
158
+ ```index.html: path/to/index.html
159
+ A dot in the captured path is required (ensures it's a file, not a bare language tag).
160
+ """
161
+ pattern = re.compile(
162
+ r"```(?:filename|file|[\w.+-]+):\s*([\w./\\-]+\.[\w]+)\n(.*?)```",
163
+ re.DOTALL,
164
+ )
165
+ seen = set()
166
+ files = []
167
+ for m in pattern.finditer(text):
168
+ fname = m.group(1).strip()
169
+ if fname not in seen:
170
+ seen.add(fname)
171
+ files.append({"filename": fname, "content": m.group(2).rstrip()})
172
+ return files
173
 
174
 
175
  def build_zip(contents: dict, code_text: str, review_text: str) -> str:
176
+ """Create a ZIP with all generated docs and code files. Returns zip path."""
177
  tmpdir = Path(tempfile.mkdtemp())
178
 
 
179
  docs = {
180
+ "strategy.md": f"# Strategy\n\n{contents.get('strategy', '')}",
181
+ "design.md": f"# Design Spec\n\n{contents.get('design', '')}",
182
  "build_output.md": f"# Build Output\n\n{code_text}",
183
+ "review.md": f"# Code Review\n\n{review_text}",
184
  }
185
  for fname, text in docs.items():
186
  (tmpdir / fname).write_text(text, encoding="utf-8")
187
 
 
188
  code_dir = tmpdir / "code"
189
  code_dir.mkdir()
190
  for f in extract_code_files(code_text):
191
  dest = code_dir / f["filename"]
192
  dest.parent.mkdir(parents=True, exist_ok=True)
193
  dest.write_text(f["content"], encoding="utf-8")
 
 
194
  for f in extract_code_files(review_text):
195
  dest = code_dir / f["filename"]
196
  dest.parent.mkdir(parents=True, exist_ok=True)
197
  dest.write_text(f["content"], encoding="utf-8")
198
 
 
199
  zip_path = str(tmpdir / "project.zip")
200
  with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
201
  for fpath in tmpdir.rglob("*"):
202
  if fpath.is_file() and fpath.name != "project.zip":
203
  zf.write(fpath, fpath.relative_to(tmpdir))
 
204
  return zip_path
205
 
206
 
207
  def set_env_keys(**kwargs):
 
208
  mapping = {
209
  "groq_key": "GROQ_API_KEY",
210
  "anthropic_key": "ANTHROPIC_API_KEY",
 
221
 
222
  def make_agent_config(name, provider, model, temperature, max_tokens, stage):
223
  return {
224
+ "name": name,
225
+ "provider": provider,
226
+ "model": model,
227
+ "temperature": temperature,
228
+ "max_tokens": max_tokens,
229
  "system_prompt": SYSTEM_PROMPTS[stage],
230
  }
231
 
232
 
233
+ # โ”€โ”€ Background NVIDIA health check on startup โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
234
+
235
+ def _startup_health_check():
236
+ """Run silently in background so health data is ready when user hits Build."""
237
+ key = os.environ.get("NVIDIA_API_KEY", "")
238
+ if key:
239
+ run_nvidia_health_check(key)
240
+
241
+ threading.Thread(target=_startup_health_check, daemon=True).start()
242
+
243
+
244
+ # โ”€โ”€ Pipeline โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
245
 
246
  def run_build_pipeline(
247
  prompt,
248
+ ref_image, # PIL Image or None
249
  groq_key, anthropic_key, nvidia_key, kimi_key, hf_token, openai_key,
250
  s_provider, s_model,
251
  d_provider, d_model,
252
  b_provider, b_model,
253
  r_provider, r_model,
254
  ):
255
+ """Generator โ€” yields (status, strategy, design, builder, reviewer, zip) after each stage."""
 
 
 
256
  EMPTY = ("", "", "", "", None)
257
 
258
  if not prompt.strip():
259
  yield ("โŒ Please enter a prompt first.", *EMPTY)
260
  return
261
 
 
262
  set_env_keys(
263
  groq_key=groq_key, anthropic_key=anthropic_key,
264
  nvidia_key=nvidia_key, kimi_key=kimi_key,
265
  hf_token=hf_token, openai_key=openai_key,
266
  )
267
 
268
+ # Convert reference image to base64 once
269
+ image_b64 = _encode_image(ref_image)
270
+ image_note = "\n\n*[A reference image has been provided above โ€” study it carefully.]*" if image_b64 else ""
271
+
272
+ strategy_cfg = make_agent_config("Strategy Agent", s_provider, s_model, 0.7, 2048, "strategy")
273
+ design_cfg = make_agent_config("Design Agent", d_provider, d_model, 0.6, 2048, "design")
274
+ builder_cfg = make_agent_config("Builder Agent", b_provider, b_model, 0.2, 8192, "builder")
275
  reviewer_cfg = make_agent_config("Code Review Agent", r_provider, r_model, 0.4, 4096, "reviewer")
276
 
277
  s_out = d_out = b_out = r_out = ""
278
 
279
+ # Stage 1 โ€” Strategy
280
+ yield (f"โณ **Stage 1/4** โ€” Strategy Agent runningโ€ฆ ({s_provider}/{s_model})", s_out, d_out, b_out, r_out, None)
281
  try:
282
  t0 = time.time()
283
+ res = run_agent_with_fallback(
284
+ strategy_cfg,
285
+ f"User's build request:\n\n{prompt}{image_note}\n\nProduce a comprehensive strategy document.",
286
+ "strategy", image_b64=image_b64,
287
  )
288
+ s_out = res["content"]
 
289
  yield (
290
+ f"โœ… Strategy done ({res['input_tokens']+res['output_tokens']:,} tok, {round(time.time()-t0,1)}s) "
291
+ f"โ€” used **{res['model']}**\nโณ **Stage 2/4** โ€” Design Agent runningโ€ฆ",
292
  s_out, d_out, b_out, r_out, None,
293
  )
294
  except Exception as e:
295
  yield (f"โŒ Strategy Agent failed: {e}", s_out, d_out, b_out, r_out, None)
296
  return
297
 
298
+ # Stage 2 โ€” Design
299
  try:
300
  t0 = time.time()
301
+ res = run_agent_with_fallback(
302
+ design_cfg,
303
+ f"Original request:\n{prompt}{image_note}\n\n--- Strategy ---\n{s_out}\n\nProduce a detailed design spec.",
304
+ "design", image_b64=image_b64,
305
  )
306
+ d_out = res["content"]
 
307
  yield (
308
+ f"โœ… Design done ({res['input_tokens']+res['output_tokens']:,} tok, {round(time.time()-t0,1)}s) "
309
+ f"โ€” used **{res['model']}**\nโณ **Stage 3/4** โ€” Builder Agent runningโ€ฆ *(this takes longest)*",
310
  s_out, d_out, b_out, r_out, None,
311
  )
312
  except Exception as e:
313
  yield (f"โŒ Design Agent failed: {e}", s_out, d_out, b_out, r_out, None)
314
  return
315
 
316
+ # Stage 3 โ€” Builder (no image โ€” works from text spec)
317
  try:
318
  t0 = time.time()
319
+ res = run_agent_with_fallback(
320
+ builder_cfg,
321
  (
322
  f"Original request:\n{prompt}\n\n"
323
  f"--- Strategy ---\n{s_out}\n\n"
324
  f"--- Design Spec ---\n{d_out}\n\n"
325
  "Build the complete, working implementation now. "
326
+ "Output every file using EXACTLY this format:\n\n"
327
+ "```filename: path/to/file.ext\n[contents]\n```"
328
  ),
329
+ "builder",
330
  )
331
+ b_out = res["content"]
 
332
  yield (
333
+ f"โœ… Build done ({res['input_tokens']+res['output_tokens']:,} tok, {round(time.time()-t0,1)}s) "
334
+ f"โ€” used **{res['model']}**\nโณ **Stage 4/4** โ€” Code Review Agent runningโ€ฆ",
335
  s_out, d_out, b_out, r_out, None,
336
  )
337
  except Exception as e:
338
  yield (f"โŒ Builder Agent failed: {e}", s_out, d_out, b_out, r_out, None)
339
  return
340
 
341
+ # Stage 4 โ€” Review
342
  try:
343
  t0 = time.time()
344
+ res = run_agent_with_fallback(
345
+ reviewer_cfg,
346
  f"Original request:\n{prompt}\n\n--- Code to Review ---\n{b_out}",
347
+ "reviewer",
348
  )
349
+ r_out = res["content"]
 
350
  except Exception as e:
351
  yield (f"โŒ Code Review Agent failed: {e}", s_out, d_out, b_out, r_out, None)
352
  return
353
 
354
+ # Package
355
  try:
356
+ zip_path = build_zip({"strategy": s_out, "design": d_out}, b_out, r_out)
357
+ except Exception:
 
 
 
358
  zip_path = None
359
 
360
+ code_files = {f["filename"] for f in extract_code_files(b_out) + extract_code_files(r_out)}
 
361
 
362
  yield (
363
+ f"๐ŸŽ‰ **Pipeline complete!** {len(code_files)} file(s) generated. "
364
+ f"Click **Download Project** to get your ZIP.",
365
  s_out, d_out, b_out, r_out, zip_path,
366
  )
367
 
368
 
369
+ # โ”€โ”€ UI helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
370
 
371
  def apply_preset(preset_name):
 
372
  p = PRESETS.get(preset_name, PRESETS["๐Ÿ†“ All Groq (Free)"])
373
  return (
374
  p["strategy"][0], p["strategy"][1],
 
379
 
380
 
381
  def update_model_dropdown(provider):
 
382
  models = PROVIDER_MODELS.get(provider, [])
383
  default = models[0] if models else ""
384
  return gr.Dropdown(choices=models, value=default)
385
 
386
 
387
+ def do_health_check(nvidia_key_input):
388
+ key = nvidia_key_input.strip() or os.environ.get("NVIDIA_API_KEY", "")
389
+ if not key:
390
+ return "โŒ No NVIDIA API key found. Enter it in the field above or add it as an HF Secret."
391
+ if key:
392
+ os.environ["NVIDIA_API_KEY"] = key
393
+ reset_health_cache()
394
+ run_nvidia_health_check(key, force=True)
395
+ return get_health_summary()
396
+
397
+
398
  # โ”€โ”€ UI โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
399
 
400
  CSS = """
401
  .agent-panel { border-radius: 12px !important; }
402
+ .status-box { font-size: 15px; font-weight: 500; }
403
+ footer { display: none !important; }
404
+ #title-row { text-align: center; margin-bottom: 8px; }
 
405
  """
406
 
407
  with gr.Blocks(
 
410
  css=CSS,
411
  ) as demo:
412
 
 
413
  gr.Markdown("""
414
  # ๐Ÿค– Multi-Agent Builder
415
  **Strategy โ†’ Design โ†’ Build โ†’ Code Review** โ€” four AI agents, one prompt, complete project.
 
419
 
420
  # โ”€โ”€ TAB 1: SETTINGS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
421
  with gr.Tab("๐Ÿ”‘ Settings"):
422
+ gr.Markdown("### API Keys")
423
+ gr.Markdown(
424
+ "Keys are stored in your browser session only โ€” never saved to disk. "
425
+ "If you've added keys as **HF Space Secrets**, leave those fields blank."
426
+ )
427
  with gr.Row():
428
  with gr.Column():
429
  groq_key = gr.Textbox(label="๐ŸŸข Groq API Key (Free tier)", type="password",
 
440
  hf_token = gr.Textbox(label="๐Ÿค— HuggingFace Token", type="password",
441
  placeholder="hf_...", value=os.environ.get("HF_TOKEN", ""))
442
 
443
+ gr.Markdown("---")
444
+
445
+ # NVIDIA Health Check section
446
+ gr.Markdown("### ๐ŸŽฎ NVIDIA Model Health Check")
447
+ gr.Markdown(
448
+ "Click below to ping all NVIDIA NIM models and find out which ones are currently "
449
+ "responding. The pipeline will automatically use healthy models and fall back gracefully."
450
+ )
451
+ health_btn = gr.Button("๐Ÿ” Check NVIDIA Models", variant="secondary")
452
+ health_md = gr.Markdown("*Click above to run the health check.*")
453
+ health_btn.click(fn=do_health_check, inputs=[nvidia_key], outputs=[health_md])
454
+
455
  gr.Markdown("---")
456
  gr.Markdown("### Agent Configuration")
457
  gr.Markdown("Select a preset to configure all agents at once, or set each agent individually below.")
458
 
459
+ with gr.Row():
460
+ preset_dd = gr.Dropdown(choices=list(PRESETS.keys()), value="๐Ÿ†“ All Groq (Free)",
461
+ label="Quick Preset", scale=2)
462
+ apply_btn = gr.Button("Apply Preset โ†’", scale=1, variant="secondary")
 
 
 
463
 
464
  gr.Markdown("#### Per-Agent Settings")
465
 
 
473
  with gr.Group():
474
  gr.Markdown(f"**{icon} {label}**")
475
  with gr.Row():
476
+ prov = gr.Dropdown(choices=list(PROVIDER_MODELS.keys()), value="groq",
477
+ label="Provider", scale=1)
478
+ mod = gr.Dropdown(choices=PROVIDER_MODELS["groq"],
479
+ value="llama-3.3-70b-versatile",
480
+ label="Model", scale=2)
 
 
 
 
 
 
 
481
  prov.change(fn=update_model_dropdown, inputs=prov, outputs=mod)
482
  agent_rows[stage] = (prov, mod)
483
 
 
489
  apply_btn.click(
490
  fn=apply_preset,
491
  inputs=[preset_dd],
492
+ outputs=[s_provider, s_model, d_provider, d_model,
493
+ b_provider, b_model, r_provider, r_model],
494
  )
495
 
496
  # โ”€โ”€ TAB 2: BUILD โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
508
  ),
509
  lines=5,
510
  )
511
+
512
+ # Reference image upload
513
+ ref_image = gr.Image(
514
+ label="๐Ÿ“Ž Reference Image (optional) โ€” upload a mockup, screenshot, or diagram for agents to study",
515
+ type="pil",
516
+ sources=["upload"],
517
+ )
518
+
519
  build_btn = gr.Button("๐Ÿš€ Build It", variant="primary", size="lg")
520
 
521
  with gr.Column(scale=2):
 
527
  | 2 | ๐ŸŽจ Design | Architecture, file tree, data models |
528
  | 3 | ๐Ÿ”จ Builder | Complete, working code |
529
  | 4 | ๐Ÿ” Reviewer | Bug hunt + improvements |
530
+
531
+ **๐Ÿ’ก Reference Image**
532
+ Upload a mockup, screenshot, or diagram and the Strategy + Design agents will study it.
533
+ Vision-capable models: Anthropic Claude, NVIDIA llama-3.2-vision, GPT-4o.
534
  """)
535
 
536
  status_md = gr.Markdown(
 
546
 
547
  with gr.Accordion("๐Ÿง  Strategy", open=False, elem_classes=["agent-panel"]):
548
  strategy_md = gr.Markdown("*Not run yet.*")
 
549
  with gr.Accordion("๐ŸŽจ Design Spec", open=False, elem_classes=["agent-panel"]):
550
  design_md = gr.Markdown("*Not run yet.*")
 
551
  with gr.Accordion("๐Ÿ”จ Build Output", open=False, elem_classes=["agent-panel"]):
552
  builder_md = gr.Markdown("*Not run yet.*")
 
553
  with gr.Accordion("๐Ÿ” Code Review", open=False, elem_classes=["agent-panel"]):
554
  reviewer_md = gr.Markdown("*Not run yet.*")
555
 
 
556
  build_btn.click(
557
  fn=run_build_pipeline,
558
  inputs=[
559
+ prompt_input, ref_image,
560
  groq_key, anthropic_key, nvidia_key, kimi_key, hf_token, openai_key,
561
  s_provider, s_model,
562
  d_provider, d_model,
 
571
  gr.Markdown("""
572
  ## Getting Started
573
 
574
+ ### 1. Get a Free API Key (Groq โ€” easiest)
575
  1. Go to [console.groq.com](https://console.groq.com) and sign up
576
+ 2. Create an API key and paste it in **๐Ÿ”‘ Settings โ†’ Groq API Key**
577
+ 3. The **๐Ÿ†“ All Groq (Free)** preset is already selected โ€” you're ready
578
+
579
+ ### 2. Use NVIDIA NIM (Free $200 credits, best for coding)
580
+ 1. Go to [build.nvidia.com](https://build.nvidia.com) and sign up
581
+ 2. Click **Get API Key** to generate your key
582
+ 3. Paste it in **๐Ÿ”‘ Settings โ†’ NVIDIA NIM API Key**
583
+ 4. Click **๐Ÿ” Check NVIDIA Models** to see which models are live right now
584
+ 5. Select the **๐ŸŽฎ NVIDIA NIM** preset โ€” the pipeline auto-picks the best available model
585
+
586
+ ### 3. Upload a Reference Image
587
+ - In the **๐Ÿš€ Build** tab, upload a mockup, screenshot, or diagram
588
+ - The Strategy and Design agents will study it alongside your text prompt
589
+ - Works best with vision-capable models: Anthropic Claude, NVIDIA llama-3.2-vision, GPT-4o
590
+
591
+ ### 4. Build your first project
592
  1. Go to the **๐Ÿš€ Build** tab
593
+ 2. Type what you want (be specific โ€” more detail = better output)
594
+ 3. Optionally upload a reference image
595
+ 4. Click **Build It** and watch the 4 agents run
596
+ 5. Download the ZIP โ€” open `code/index.html` (or run the Python file) directly
 
 
 
 
 
597
 
598
  ---
599
 
600
+ ## Provider Guide
601
+ | Provider | Free Tier | Best For |
602
+ |----------|-----------|----------|
603
+ | **Groq** | 14k req/day | Everything โ€” fastest inference |
604
+ | **NVIDIA NIM** | $200 credits on signup | Coding (Qwen2.5-Coder), vision |
605
+ | **Anthropic** | Paid (best quality) | Strategy + Review + vision |
606
+ | **Kimi** | Credits on signup | Long-context builds |
607
+ | **HuggingFace** | Rate-limited | Experimenting |
 
 
608
 
609
  ## Prompt Tips
610
+ - โœ… **Be specific**: "Build a Pomodoro timer web app with dark mode, sound alerts, and local storage for stats"
611
  - โœ… **Name your stack**: "Using FastAPI and PostgreSQL, build a REST API for a blog"
612
+ - โœ… **Upload a reference**: attach a screenshot so agents can see exactly what you mean
613
+ - โŒ **Too vague**: "Build an app" โ†’ agents will make assumptions that may not match what you want
614
  """)
615
 
616
  gr.Markdown(
617
+ "<center><sub>Multi-Agent Builder ยท Built with Gradio ยท "
618
+ "Powered by your choice of AI provider</sub></center>"
619
  )
620
 
621
 
 
 
622
  if __name__ == "__main__":
623
  demo.launch()