Madras1 commited on
Commit
7f9880a
·
verified ·
1 Parent(s): dc4d05e

Upload 13 files

Browse files
Files changed (2) hide show
  1. app.py +3 -1
  2. jade/webdev.py +167 -64
app.py CHANGED
@@ -142,13 +142,15 @@ async def handle_chat(request: UserRequest):
142
  class WebDevRequest(BaseModel):
143
  prompt: str
144
  existing_code: str | None = None
 
145
 
146
  @app.post("/webdev/generate")
147
  async def handle_webdev(request: WebDevRequest):
148
  try:
149
  result = webdev_agent.generate(
150
  prompt=request.prompt,
151
- refine_code=request.existing_code
 
152
  )
153
  return result
154
  except Exception as e:
 
142
  class WebDevRequest(BaseModel):
143
  prompt: str
144
  existing_code: str | None = None
145
+ mode: str = "html" # "html" or "react"
146
 
147
  @app.post("/webdev/generate")
148
  async def handle_webdev(request: WebDevRequest):
149
  try:
150
  result = webdev_agent.generate(
151
  prompt=request.prompt,
152
+ refine_code=request.existing_code,
153
+ mode=request.mode
154
  )
155
  return result
156
  except Exception as e:
jade/webdev.py CHANGED
@@ -1,9 +1,10 @@
1
  """
2
  Jade Web Dev - Vibe Coder
3
- AI-powered web code generator
4
  """
5
 
6
  import os
 
7
  import logging
8
  from groq import Groq
9
 
@@ -16,66 +17,170 @@ class WebDevAgent:
16
  logger.warning("GROQ_API_KEY not set. WebDev agent may fail.")
17
 
18
  self.client = Groq(api_key=self.groq_api_key)
19
- self.model = "moonshotai/kimi-k2-instruct-0905" # Good for code generation
20
 
21
- self.system_prompt = """You are an elite web developer AI creating stunning, FULLY FUNCTIONAL websites.
 
22
 
23
  TECHNICAL REQUIREMENTS:
24
  1. Use Tailwind CSS via CDN: <script src="https://cdn.tailwindcss.com"></script>
25
  2. Output ONLY valid HTML - no markdown, no explanations, no code blocks
26
  3. MUST include functional JavaScript in <script> tags
27
- 4. ALL styling must use Tailwind classes - no inline CSS
28
  5. Must be a complete, standalone HTML file starting with <!DOCTYPE html>
29
 
30
- JAVASCRIPT INTERACTIVITY (CRITICAL):
31
  1. ALL buttons MUST have onclick handlers that DO something
32
  2. Modals must open/close when clicked
33
  3. Navigation tabs/links must show/hide content sections
34
  4. Forms must have validation and show feedback
35
  5. Counters, toggles, accordions must work
36
- 6. Use event listeners for all interactive elements
37
- 7. Mobile menu toggle must work
38
- 8. Add loading states, animations on interaction
39
 
40
  DESIGN REQUIREMENTS:
41
- 1. Use modern, premium aesthetics (gradients, shadows, rounded corners)
42
- 2. Dark mode by default with rich colors (slate, zinc, purple, blue accents)
43
- 3. Smooth hover animations (hover:scale-105, hover:shadow-lg)
44
- 4. Professional typography (font-sans, proper spacing)
45
- 5. Responsive design (flex, grid, md:, lg: breakpoints)
46
- 6. Use placeholder images from picsum.photos
47
- 7. Include relevant icons using SVG
48
- 8. Add micro-interactions (transitions, transforms)
49
-
50
- EXAMPLE OF WORKING BUTTON:
51
- <button onclick="alert('Clicked!')" class="bg-purple-600 hover:bg-purple-700 px-4 py-2 rounded">
52
- Click Me
53
- </button>
54
-
55
- EXAMPLE OF WORKING MODAL:
56
- <div id="modal" class="hidden fixed inset-0 bg-black/50 flex items-center justify-center">
57
- <div class="bg-slate-800 p-6 rounded-xl">
58
- <button onclick="document.getElementById('modal').classList.add('hidden')">Close</button>
59
- </div>
60
- </div>
61
- <button onclick="document.getElementById('modal').classList.remove('hidden')">Open Modal</button>
62
 
63
  OUTPUT: Raw HTML only, starting with <!DOCTYPE html>"""
64
 
65
- def generate(self, prompt: str, refine_code: str = None) -> dict:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  """
67
  Generate or refine code based on prompt
68
 
69
  Args:
70
- prompt: User's description of the website
71
  refine_code: Optional existing code to refine
 
72
 
73
  Returns:
74
- dict with 'code' and 'success' keys
75
  """
76
  try:
77
- if refine_code:
78
- user_message = f"""Current code:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  ```html
80
  {refine_code}
81
  ```
@@ -83,36 +188,34 @@ OUTPUT: Raw HTML only, starting with <!DOCTYPE html>"""
83
  User feedback: {prompt}
84
 
85
  Update the code based on the feedback. Output the complete updated HTML file."""
86
- else:
87
- user_message = f"Create a website: {prompt}"
88
-
89
- response = self.client.chat.completions.create(
90
- model=self.model,
91
- messages=[
92
- {"role": "system", "content": self.system_prompt},
93
- {"role": "user", "content": user_message}
94
- ],
95
- temperature=0.7,
96
- max_tokens=8000
97
- )
98
-
99
- code = response.choices[0].message.content
100
-
101
- # Clean up any markdown formatting if present
102
- code = code.strip()
103
- if code.startswith("```html"):
104
- code = code[7:]
105
- if code.startswith("```"):
106
- code = code[3:]
107
- if code.endswith("```"):
108
- code = code[:-3]
109
- code = code.strip()
110
-
111
- # Ensure it starts with doctype
112
- if not code.lower().startswith("<!doctype"):
113
- code = "<!DOCTYPE html>\n" + code
114
-
115
- return {"success": True, "code": code}
116
 
117
  except Exception as e:
118
  logger.error(f"WebDev generation error: {e}")
 
1
  """
2
  Jade Web Dev - Vibe Coder
3
+ AI-powered web code generator with React/Sandpack support
4
  """
5
 
6
  import os
7
+ import json
8
  import logging
9
  from groq import Groq
10
 
 
17
  logger.warning("GROQ_API_KEY not set. WebDev agent may fail.")
18
 
19
  self.client = Groq(api_key=self.groq_api_key)
20
+ self.model = "moonshotai/kimi-k2-instruct-0905"
21
 
22
+ # HTML mode prompt
23
+ self.html_prompt = """You are an elite web developer AI creating stunning, FULLY FUNCTIONAL websites.
24
 
25
  TECHNICAL REQUIREMENTS:
26
  1. Use Tailwind CSS via CDN: <script src="https://cdn.tailwindcss.com"></script>
27
  2. Output ONLY valid HTML - no markdown, no explanations, no code blocks
28
  3. MUST include functional JavaScript in <script> tags
29
+ 4. ALL styling must use Tailwind classes
30
  5. Must be a complete, standalone HTML file starting with <!DOCTYPE html>
31
 
32
+ JAVASCRIPT INTERACTIVITY:
33
  1. ALL buttons MUST have onclick handlers that DO something
34
  2. Modals must open/close when clicked
35
  3. Navigation tabs/links must show/hide content sections
36
  4. Forms must have validation and show feedback
37
  5. Counters, toggles, accordions must work
 
 
 
38
 
39
  DESIGN REQUIREMENTS:
40
+ 1. Modern aesthetics (gradients, shadows, rounded corners)
41
+ 2. Dark mode by default (slate, zinc, purple accents)
42
+ 3. Smooth hover animations
43
+ 4. Responsive design (flex, grid, md:, lg: breakpoints)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  OUTPUT: Raw HTML only, starting with <!DOCTYPE html>"""
46
 
47
+ # React mode prompt
48
+ self.react_prompt = """You are an elite React developer AI creating stunning, production-ready React applications.
49
+
50
+ OUTPUT FORMAT - CRITICAL:
51
+ You MUST output a valid JSON object with file contents. No markdown, no explanations.
52
+ The response must be parseable JSON with this exact structure:
53
+
54
+ {
55
+ "App.tsx": "// Main app component code here",
56
+ "components/ComponentName.tsx": "// Component code here",
57
+ "styles.css": "/* CSS code here */"
58
+ }
59
+
60
+ TECHNICAL REQUIREMENTS:
61
+ 1. Use React with TypeScript (.tsx files)
62
+ 2. Use Tailwind CSS for all styling (classes only)
63
+ 3. Create modular components in components/ folder
64
+ 4. App.tsx is the main entry point
65
+ 5. Use React hooks (useState, useEffect, etc)
66
+ 6. All components must be functional components
67
+ 7. Export components as default exports
68
+
69
+ COMPONENT STRUCTURE:
70
+ - App.tsx: Main app with routing/state
71
+ - components/: Reusable components
72
+ - Each component in its own file
73
+
74
+ DESIGN REQUIREMENTS:
75
+ 1. Dark mode by default (bg-slate-900, text-white)
76
+ 2. Modern UI with gradients, shadows, rounded corners
77
+ 3. Smooth animations (transition, hover effects)
78
+ 4. Responsive (flex, grid, md:, lg: breakpoints)
79
+ 5. Professional typography
80
+
81
+ EXAMPLE App.tsx:
82
+ import React, { useState } from 'react';
83
+ import Header from './components/Header';
84
+ import Hero from './components/Hero';
85
+
86
+ export default function App() {
87
+ const [count, setCount] = useState(0);
88
+ return (
89
+ <div className="min-h-screen bg-slate-900 text-white">
90
+ <Header />
91
+ <Hero count={count} onIncrement={() => setCount(c => c + 1)} />
92
+ </div>
93
+ );
94
+ }
95
+
96
+ EXAMPLE components/Button.tsx:
97
+ import React from 'react';
98
+
99
+ interface ButtonProps {
100
+ children: React.ReactNode;
101
+ onClick?: () => void;
102
+ }
103
+
104
+ export default function Button({ children, onClick }: ButtonProps) {
105
+ return (
106
+ <button
107
+ onClick={onClick}
108
+ className="bg-purple-600 hover:bg-purple-700 px-4 py-2 rounded-lg transition"
109
+ >
110
+ {children}
111
+ </button>
112
+ );
113
+ }
114
+
115
+ REMEMBER: Output ONLY the JSON object, nothing else. No markdown code blocks."""
116
+
117
+ def generate(self, prompt: str, refine_code: str = None, mode: str = "html") -> dict:
118
  """
119
  Generate or refine code based on prompt
120
 
121
  Args:
122
+ prompt: User's description
123
  refine_code: Optional existing code to refine
124
+ mode: "html" for HTML generation, "react" for React/Sandpack
125
 
126
  Returns:
127
+ dict with code/files and success status
128
  """
129
  try:
130
+ system_prompt = self.react_prompt if mode == "react" else self.html_prompt
131
+
132
+ if mode == "react":
133
+ if refine_code:
134
+ user_message = f"""Current files:
135
+ {refine_code}
136
+
137
+ User feedback: {prompt}
138
+
139
+ Update the React app based on the feedback. Output the complete updated JSON."""
140
+ else:
141
+ user_message = f"Create a React app: {prompt}"
142
+
143
+ response = self.client.chat.completions.create(
144
+ model=self.model,
145
+ messages=[
146
+ {"role": "system", "content": system_prompt},
147
+ {"role": "user", "content": user_message}
148
+ ],
149
+ temperature=0.7,
150
+ max_tokens=16000
151
+ )
152
+
153
+ content = response.choices[0].message.content.strip()
154
+
155
+ # Clean up markdown if present
156
+ if content.startswith("```json"):
157
+ content = content[7:]
158
+ if content.startswith("```"):
159
+ content = content[3:]
160
+ if content.endswith("```"):
161
+ content = content[:-3]
162
+ content = content.strip()
163
+
164
+ # Parse JSON
165
+ try:
166
+ files = json.loads(content)
167
+ return {"success": True, "files": files, "mode": "react"}
168
+ except json.JSONDecodeError as e:
169
+ logger.error(f"Failed to parse React JSON: {e}")
170
+ # Try to extract JSON from the response
171
+ import re
172
+ match = re.search(r'\{[\s\S]*\}', content)
173
+ if match:
174
+ try:
175
+ files = json.loads(match.group())
176
+ return {"success": True, "files": files, "mode": "react"}
177
+ except:
178
+ pass
179
+ return {"success": False, "error": "Failed to parse React code"}
180
+
181
+ else: # HTML mode
182
+ if refine_code:
183
+ user_message = f"""Current code:
184
  ```html
185
  {refine_code}
186
  ```
 
188
  User feedback: {prompt}
189
 
190
  Update the code based on the feedback. Output the complete updated HTML file."""
191
+ else:
192
+ user_message = f"Create a website: {prompt}"
193
+
194
+ response = self.client.chat.completions.create(
195
+ model=self.model,
196
+ messages=[
197
+ {"role": "system", "content": system_prompt},
198
+ {"role": "user", "content": user_message}
199
+ ],
200
+ temperature=0.7,
201
+ max_tokens=8000
202
+ )
203
+
204
+ code = response.choices[0].message.content.strip()
205
+
206
+ # Clean up markdown
207
+ if code.startswith("```html"):
208
+ code = code[7:]
209
+ if code.startswith("```"):
210
+ code = code[3:]
211
+ if code.endswith("```"):
212
+ code = code[:-3]
213
+ code = code.strip()
214
+
215
+ if not code.lower().startswith("<!doctype"):
216
+ code = "<!DOCTYPE html>\n" + code
217
+
218
+ return {"success": True, "code": code, "mode": "html"}
 
 
219
 
220
  except Exception as e:
221
  logger.error(f"WebDev generation error: {e}")