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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
from typing import List, Dict, Optional
|
| 6 |
+
import time
|
| 7 |
+
import subprocess
|
| 8 |
+
import tempfile
|
| 9 |
+
import sys
|
| 10 |
+
import io
|
| 11 |
+
import contextlib
|
| 12 |
+
|
| 13 |
+
class OpenRouterCodingAgent:
|
| 14 |
+
def __init__(self):
|
| 15 |
+
# Get API key from environment variable or Hugging Face Secrets
|
| 16 |
+
self.api_key = os.getenv("OPENROUTER_API_KEY")
|
| 17 |
+
self.base_url = "https://openrouter.ai/api/v1/chat/completions"
|
| 18 |
+
|
| 19 |
+
# Free coding models (good for code generation)
|
| 20 |
+
self.free_models = [
|
| 21 |
+
"agentica-org/deepcoder-14b-preview:free",
|
| 22 |
+
"arliai/qwq-32b-arliai-rpr-v1:free",
|
| 23 |
+
"cognitivecomputations/dolphin3.0-mistral-24b:free",
|
| 24 |
+
"cognitivecomputations/dolphin3.0-r1-mistral-24b:free",
|
| 25 |
+
"deepseek/deepseek-chat-v3-0324:free",
|
| 26 |
+
"deepseek/deepseek-chat:free",
|
| 27 |
+
"deepseek/deepseek-r1-0528-qwen3-8b:free",
|
| 28 |
+
"deepseek/deepseek-r1-0528:free",
|
| 29 |
+
"deepseek/deepseek-r1-distill-llama-70b:free",
|
| 30 |
+
"deepseek/deepseek-r1-distill-qwen-14b:free",
|
| 31 |
+
"deepseek/deepseek-r1:free",
|
| 32 |
+
"deepseek/deepseek-v3-base:free",
|
| 33 |
+
"featherless/qwerky-72b:free",
|
| 34 |
+
"google/gemini-2.0-flash-exp:free",
|
| 35 |
+
"google/gemini-2.5-pro-exp-03-25",
|
| 36 |
+
"google/gemma-2-9b-it:free",
|
| 37 |
+
"google/gemma-3-12b-it:free",
|
| 38 |
+
"google/gemma-3-27b-it:free",
|
| 39 |
+
"google/gemma-3-4b-it:free",
|
| 40 |
+
"google/gemma-3n-e4b-it:free",
|
| 41 |
+
"meta-llama/llama-3.1-8b-instruct:free",
|
| 42 |
+
"meta-llama/llama-3.2-11b-vision-instruct:free",
|
| 43 |
+
"meta-llama/llama-3.2-1b-instruct:free",
|
| 44 |
+
"meta-llama/llama-3.3-70b-instruct:free",
|
| 45 |
+
"meta-llama/llama-4-maverick:free",
|
| 46 |
+
"meta-llama/llama-4-scout:free",
|
| 47 |
+
"microsoft/mai-ds-r1:free",
|
| 48 |
+
"mistralai/devstral-small:free",
|
| 49 |
+
"mistralai/mistral-7b-instruct:free",
|
| 50 |
+
"mistralai/mistral-nemo:free",
|
| 51 |
+
"mistralai/mistral-small-24b-instruct-2501:free",
|
| 52 |
+
"mistralai/mistral-small-3.1-24b-instruct:free",
|
| 53 |
+
"mistralai/mistral-small-3.2-24b-instruct:free",
|
| 54 |
+
"moonshotai/kimi-dev-72b:free",
|
| 55 |
+
"moonshotai/kimi-vl-a3b-thinking:free",
|
| 56 |
+
"nousresearch/deephermes-3-llama-3-8b-preview:free",
|
| 57 |
+
"nvidia/llama-3.1-nemotron-ultra-253b-v1:free",
|
| 58 |
+
"nvidia/llama-3.3-nemotron-super-49b-v1:free",
|
| 59 |
+
"qwen/qwen-2.5-72b-instruct:free",
|
| 60 |
+
"qwen/qwen-2.5-coder-32b-instruct:free",
|
| 61 |
+
"qwen/qwen2.5-vl-32b-instruct:free",
|
| 62 |
+
"qwen/qwen2.5-vl-72b-instruct:free",
|
| 63 |
+
"qwen/qwen3-14b:free",
|
| 64 |
+
"qwen/qwen3-235b-a22b:free",
|
| 65 |
+
"qwen/qwen3-30b-a3b:free",
|
| 66 |
+
"qwen/qwen3-32b:free",
|
| 67 |
+
"qwen/qwen3-8b:free",
|
| 68 |
+
"qwen/qwq-32b:free",
|
| 69 |
+
"rekaai/reka-flash-3:free",
|
| 70 |
+
"sarvamai/sarvam-m:free",
|
| 71 |
+
"shisa-ai/shisa-v2-llama3.3-70b:free",
|
| 72 |
+
"thudm/glm-4-32b:free",
|
| 73 |
+
"thudm/glm-z1-32b:free",
|
| 74 |
+
"tngtech/deepseek-r1t-chimera:free",
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
# Set default model (DeepSeek is excellent for coding)
|
| 78 |
+
self.default_model = "deepseek/deepseek-r1:free"
|
| 79 |
+
|
| 80 |
+
print(f"β
Coding Agent ready with {len(self.free_models)} free models")
|
| 81 |
+
|
| 82 |
+
def get_clean_model_choices(self):
|
| 83 |
+
"""Get model choices with clean names for display"""
|
| 84 |
+
choices = []
|
| 85 |
+
for model in self.free_models:
|
| 86 |
+
clean_name = model.replace(":free", "")
|
| 87 |
+
choices.append((clean_name, model))
|
| 88 |
+
return choices
|
| 89 |
+
|
| 90 |
+
def make_request(self, messages: List[Dict], model: str, temperature: float = 0.7) -> str:
|
| 91 |
+
"""Make a request to OpenRouter API"""
|
| 92 |
+
if not self.api_key:
|
| 93 |
+
return "β Error: OpenRouter API key not configured."
|
| 94 |
+
|
| 95 |
+
headers = {
|
| 96 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 97 |
+
"Content-Type": "application/json",
|
| 98 |
+
"HTTP-Referer": "https://huggingface.co/spaces",
|
| 99 |
+
"X-Title": "Free Coding Agent via OpenRouter"
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
data = {
|
| 103 |
+
"model": model,
|
| 104 |
+
"messages": messages,
|
| 105 |
+
"temperature": temperature,
|
| 106 |
+
"max_tokens": 2000,
|
| 107 |
+
"stream": False
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
response = requests.post(self.base_url, headers=headers, json=data, timeout=60)
|
| 112 |
+
response.raise_for_status()
|
| 113 |
+
result = response.json()
|
| 114 |
+
|
| 115 |
+
if 'choices' in result and len(result['choices']) > 0:
|
| 116 |
+
return result['choices'][0]['message']['content']
|
| 117 |
+
else:
|
| 118 |
+
return "β Error: No response generated"
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
return f"β Error: {str(e)}"
|
| 122 |
+
|
| 123 |
+
# Initialize the coding agent
|
| 124 |
+
coding_agent = OpenRouterCodingAgent()
|
| 125 |
+
|
| 126 |
+
def execute_python_code(code: str) -> str:
|
| 127 |
+
"""Execute Python code safely and return output"""
|
| 128 |
+
if not code.strip():
|
| 129 |
+
return ""
|
| 130 |
+
|
| 131 |
+
# Create string buffer to capture output
|
| 132 |
+
output = io.StringIO()
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
# Redirect stdout to capture print statements
|
| 136 |
+
with contextlib.redirect_stdout(output):
|
| 137 |
+
# Execute the code
|
| 138 |
+
exec(code)
|
| 139 |
+
|
| 140 |
+
result = output.getvalue()
|
| 141 |
+
return result if result else "β
Code executed successfully (no output)"
|
| 142 |
+
|
| 143 |
+
except Exception as e:
|
| 144 |
+
return f"β Error: {str(e)}"
|
| 145 |
+
|
| 146 |
+
def create_web_preview(html: str, css: str, js: str) -> str:
|
| 147 |
+
"""Create a complete HTML page with CSS and JS"""
|
| 148 |
+
return f"""
|
| 149 |
+
<!DOCTYPE html>
|
| 150 |
+
<html lang="en">
|
| 151 |
+
<head>
|
| 152 |
+
<meta charset="UTF-8">
|
| 153 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 154 |
+
<title>Live Preview</title>
|
| 155 |
+
<style>
|
| 156 |
+
body {{
|
| 157 |
+
margin: 0;
|
| 158 |
+
padding: 20px;
|
| 159 |
+
font-family: Arial, sans-serif;
|
| 160 |
+
}}
|
| 161 |
+
{css}
|
| 162 |
+
</style>
|
| 163 |
+
</head>
|
| 164 |
+
<body>
|
| 165 |
+
{html}
|
| 166 |
+
<script>
|
| 167 |
+
{js}
|
| 168 |
+
</script>
|
| 169 |
+
</body>
|
| 170 |
+
</html>
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
def generate_code(prompt: str, model: str, code_type: str, current_code: str = "") -> str:
|
| 174 |
+
"""Generate code using OpenRouter API"""
|
| 175 |
+
system_prompts = {
|
| 176 |
+
"html": "You are an expert HTML developer. Generate clean, semantic HTML code based on the user's request. Only return the HTML code, no explanations.",
|
| 177 |
+
"css": "You are an expert CSS developer. Generate modern, responsive CSS code based on the user's request. Only return the CSS code, no explanations.",
|
| 178 |
+
"javascript": "You are an expert JavaScript developer. Generate clean, modern JavaScript code based on the user's request. Only return the JavaScript code, no explanations.",
|
| 179 |
+
"python": "You are an expert Python developer. Generate clean, working Python code based on the user's request. Only return the Python code, no explanations."
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
context = f"\nCurrent {code_type} code:\n```{code_type}\n{current_code}\n```\n" if current_code.strip() else ""
|
| 183 |
+
|
| 184 |
+
messages = [
|
| 185 |
+
{"role": "system", "content": system_prompts.get(code_type, "You are a helpful coding assistant.")},
|
| 186 |
+
{"role": "user", "content": f"{prompt}{context}"}
|
| 187 |
+
]
|
| 188 |
+
|
| 189 |
+
response = coding_agent.make_request(messages, model)
|
| 190 |
+
|
| 191 |
+
# Clean up the response to extract just the code
|
| 192 |
+
if "```" in response:
|
| 193 |
+
# Extract code from markdown code blocks
|
| 194 |
+
parts = response.split("```")
|
| 195 |
+
for i, part in enumerate(parts):
|
| 196 |
+
if i % 2 == 1: # Odd indices are code blocks
|
| 197 |
+
# Remove language identifier if present
|
| 198 |
+
lines = part.strip().split('\n')
|
| 199 |
+
if lines[0].strip() in ['html', 'css', 'javascript', 'js', 'python', 'py']:
|
| 200 |
+
return '\n'.join(lines[1:])
|
| 201 |
+
return part.strip()
|
| 202 |
+
|
| 203 |
+
return response.strip()
|
| 204 |
+
|
| 205 |
+
def chat_with_agent(message: str, history: List, model: str) -> tuple:
|
| 206 |
+
"""Chat with the coding agent"""
|
| 207 |
+
if not message.strip():
|
| 208 |
+
return history, ""
|
| 209 |
+
|
| 210 |
+
messages = [
|
| 211 |
+
{"role": "system", "content": "You are a helpful coding assistant. Help users with programming questions, debugging, and code explanations."}
|
| 212 |
+
]
|
| 213 |
+
|
| 214 |
+
# Add conversation history
|
| 215 |
+
for user_msg, assistant_msg in history:
|
| 216 |
+
if user_msg:
|
| 217 |
+
messages.append({"role": "user", "content": user_msg})
|
| 218 |
+
if assistant_msg:
|
| 219 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
| 220 |
+
|
| 221 |
+
# Add current message
|
| 222 |
+
messages.append({"role": "user", "content": message})
|
| 223 |
+
|
| 224 |
+
# Get response
|
| 225 |
+
response = coding_agent.make_request(messages, model, temperature=0.7)
|
| 226 |
+
|
| 227 |
+
# Add to history
|
| 228 |
+
history.append((message, response))
|
| 229 |
+
return history, ""
|
| 230 |
+
|
| 231 |
+
# Create the Gradio interface
|
| 232 |
+
with gr.Blocks(
|
| 233 |
+
title="Free Coding Agent - CodePen Style",
|
| 234 |
+
theme=gr.themes.Soft(),
|
| 235 |
+
css="""
|
| 236 |
+
.code-container { font-family: 'Courier New', monospace; }
|
| 237 |
+
.preview-container { border: 1px solid #ddd; border-radius: 8px; }
|
| 238 |
+
.main-header { text-align: center; margin-bottom: 2em; }
|
| 239 |
+
""") as demo:
|
| 240 |
+
|
| 241 |
+
gr.HTML("""
|
| 242 |
+
<div class="main-header">
|
| 243 |
+
<h1>π Free Coding Agent</h1>
|
| 244 |
+
<p>CodePen-style environment with AI assistance</p>
|
| 245 |
+
<p style="color: #22c55e; font-weight: bold;">β¨ Generate, edit, and run code with AI help!</p>
|
| 246 |
+
</div>
|
| 247 |
+
""")
|
| 248 |
+
|
| 249 |
+
with gr.Row():
|
| 250 |
+
# Left Panel - Code Editors and AI
|
| 251 |
+
with gr.Column(scale=1):
|
| 252 |
+
gr.Markdown("### π€ AI Coding Assistant")
|
| 253 |
+
|
| 254 |
+
model_dropdown = gr.Dropdown(
|
| 255 |
+
choices=coding_agent.get_clean_model_choices(),
|
| 256 |
+
value=coding_agent.default_model,
|
| 257 |
+
label="AI Model",
|
| 258 |
+
info="Choose your coding AI"
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
# AI Chat Interface
|
| 262 |
+
with gr.Accordion("π¬ Chat with AI", open=True):
|
| 263 |
+
chatbot = gr.Chatbot(height=300, show_label=False)
|
| 264 |
+
chat_input = gr.Textbox(
|
| 265 |
+
placeholder="Ask the AI about coding, debugging, or request code generation...",
|
| 266 |
+
show_label=False
|
| 267 |
+
)
|
| 268 |
+
chat_btn = gr.Button("Send", variant="primary")
|
| 269 |
+
|
| 270 |
+
# Code Generation Tools
|
| 271 |
+
gr.Markdown("### π οΈ Code Generation")
|
| 272 |
+
|
| 273 |
+
code_type = gr.Radio(
|
| 274 |
+
choices=["html", "css", "javascript", "python"],
|
| 275 |
+
value="html",
|
| 276 |
+
label="Code Type"
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
code_prompt = gr.Textbox(
|
| 280 |
+
placeholder="Describe what you want to generate...",
|
| 281 |
+
label="Code Request",
|
| 282 |
+
lines=2
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
generate_btn = gr.Button("π― Generate Code", variant="secondary")
|
| 286 |
+
|
| 287 |
+
# Right Panel - Code Editors
|
| 288 |
+
with gr.Column(scale=2):
|
| 289 |
+
gr.Markdown("### π Code Editors")
|
| 290 |
+
|
| 291 |
+
with gr.Tabs():
|
| 292 |
+
with gr.Tab("HTML"):
|
| 293 |
+
html_code = gr.Code(
|
| 294 |
+
value="<h1>Hello World!</h1>\n<p>Start coding here...</p>",
|
| 295 |
+
language="html",
|
| 296 |
+
label="HTML",
|
| 297 |
+
lines=15
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
with gr.Tab("CSS"):
|
| 301 |
+
css_code = gr.Code(
|
| 302 |
+
value="body {\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n text-align: center;\n padding: 50px;\n}",
|
| 303 |
+
language="css",
|
| 304 |
+
label="CSS",
|
| 305 |
+
lines=15
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
with gr.Tab("JavaScript"):
|
| 309 |
+
js_code = gr.Code(
|
| 310 |
+
value="console.log('Hello from JavaScript!');\n\n// Add your JavaScript here",
|
| 311 |
+
language="javascript",
|
| 312 |
+
label="JavaScript",
|
| 313 |
+
lines=15
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
with gr.Tab("Python"):
|
| 317 |
+
python_code = gr.Code(
|
| 318 |
+
value="print('Hello from Python!')\n\n# Add your Python code here",
|
| 319 |
+
language="python",
|
| 320 |
+
label="Python",
|
| 321 |
+
lines=15
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
with gr.Row():
|
| 325 |
+
# Preview Panel
|
| 326 |
+
with gr.Column():
|
| 327 |
+
gr.Markdown("### π Live Preview")
|
| 328 |
+
|
| 329 |
+
with gr.Tabs():
|
| 330 |
+
with gr.Tab("Web Preview"):
|
| 331 |
+
web_preview = gr.HTML(
|
| 332 |
+
value=create_web_preview(
|
| 333 |
+
"<h1>Hello World!</h1><p>Start coding here...</p>",
|
| 334 |
+
"body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-align: center; padding: 50px; }",
|
| 335 |
+
"console.log('Hello from JavaScript!');"
|
| 336 |
+
),
|
| 337 |
+
label="Preview"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
update_preview_btn = gr.Button("π Update Preview", variant="primary")
|
| 341 |
+
|
| 342 |
+
with gr.Tab("Python Output"):
|
| 343 |
+
python_output = gr.Code(
|
| 344 |
+
value="",
|
| 345 |
+
language="text",
|
| 346 |
+
label="Python Output",
|
| 347 |
+
lines=10
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
run_python_btn = gr.Button("βΆοΈ Run Python", variant="primary")
|
| 351 |
+
|
| 352 |
+
# Event Handlers
|
| 353 |
+
def update_preview(html, css, js):
|
| 354 |
+
return create_web_preview(html, css, js)
|
| 355 |
+
|
| 356 |
+
def run_python(code):
|
| 357 |
+
return execute_python_code(code)
|
| 358 |
+
|
| 359 |
+
def generate_code_handler(prompt, model, code_type, html, css, js, python):
|
| 360 |
+
current_code = {
|
| 361 |
+
"html": html,
|
| 362 |
+
"css": css,
|
| 363 |
+
"javascript": js,
|
| 364 |
+
"python": python
|
| 365 |
+
}.get(code_type, "")
|
| 366 |
+
|
| 367 |
+
generated = generate_code(prompt, model, code_type, current_code)
|
| 368 |
+
|
| 369 |
+
if code_type == "html":
|
| 370 |
+
return generated, css, js, python
|
| 371 |
+
elif code_type == "css":
|
| 372 |
+
return html, generated, js, python
|
| 373 |
+
elif code_type == "javascript":
|
| 374 |
+
return html, css, generated, python
|
| 375 |
+
elif code_type == "python":
|
| 376 |
+
return html, css, js, generated
|
| 377 |
+
|
| 378 |
+
return html, css, js, python
|
| 379 |
+
|
| 380 |
+
# Connect event handlers
|
| 381 |
+
chat_btn.click(
|
| 382 |
+
chat_with_agent,
|
| 383 |
+
inputs=[chat_input, chatbot, model_dropdown],
|
| 384 |
+
outputs=[chatbot, chat_input]
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
chat_input.submit(
|
| 388 |
+
chat_with_agent,
|
| 389 |
+
inputs=[chat_input, chatbot, model_dropdown],
|
| 390 |
+
outputs=[chatbot, chat_input]
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
update_preview_btn.click(
|
| 394 |
+
update_preview,
|
| 395 |
+
inputs=[html_code, css_code, js_code],
|
| 396 |
+
outputs=[web_preview]
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
run_python_btn.click(
|
| 400 |
+
run_python,
|
| 401 |
+
inputs=[python_code],
|
| 402 |
+
outputs=[python_output]
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
generate_btn.click(
|
| 406 |
+
generate_code_handler,
|
| 407 |
+
inputs=[code_prompt, model_dropdown, code_type, html_code, css_code, js_code, python_code],
|
| 408 |
+
outputs=[html_code, css_code, js_code, python_code]
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
# Auto-update preview when code changes
|
| 412 |
+
for code_input in [html_code, css_code, js_code]:
|
| 413 |
+
code_input.change(
|
| 414 |
+
update_preview,
|
| 415 |
+
inputs=[html_code, css_code, js_code],
|
| 416 |
+
outputs=[web_preview]
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# Launch the app
|
| 420 |
+
if __name__ == "__main__":
|
| 421 |
+
demo.launch(
|
| 422 |
+
share=False,
|
| 423 |
+
server_name="0.0.0.0",
|
| 424 |
+
server_port=7861, # Different port to avoid conflicts
|
| 425 |
+
show_error=True
|
| 426 |
+
)
|