Spaces:
Sleeping
Sleeping
File size: 12,154 Bytes
c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 c4cbbd2 432e2e3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
import gradio as gr
from huggingface_hub import InferenceClient
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
from datetime import datetime
import os
# Use Hugging Face Inference API (no model loading needed!)
# This is FREE and much faster!
AGENT_CONFIGS = {
"researcher": {
"model": "mistralai/Mistral-7B-Instruct-v0.2",
"role": "Research and gather information",
"system_prompt": "You are a research agent specialized in gathering and analyzing information. Provide detailed, well-researched responses."
},
"coder": {
"model": "bigcode/starcoder2-15b",
"role": "Generate and explain code",
"system_prompt": "You are an expert programmer. Generate clean, efficient, well-commented code."
},
"analyzer": {
"model": "mistralai/Mistral-7B-Instruct-v0.2",
"role": "Analyze data and provide insights",
"system_prompt": "You are a data analyst. Provide clear insights and actionable recommendations."
},
"writer": {
"model": "mistralai/Mistral-7B-Instruct-v0.2",
"role": "Create content and documentation",
"system_prompt": "You are a technical writer. Create clear, professional documentation and content."
}
}
class AgentSystem:
def __init__(self):
# No model loading! Using HF Inference API
self.clients = {}
self.executor = ThreadPoolExecutor(max_workers=4)
# Initialize inference clients for each agent
for agent_name in AGENT_CONFIGS.keys():
model = AGENT_CONFIGS[agent_name]["model"]
self.clients[agent_name] = InferenceClient(model=model)
print("β
Agent system initialized with Inference API!")
def generate_response(self, agent_name, task, max_tokens=300):
"""Generate response using HF Inference API"""
try:
config = AGENT_CONFIGS[agent_name]
client = self.clients[agent_name]
# Create prompt
messages = [
{
"role": "system",
"content": config["system_prompt"]
},
{
"role": "user",
"content": f"Task: {task}"
}
]
# Generate response
response_text = ""
for message in client.chat_completion(
messages=messages,
max_tokens=max_tokens,
temperature=0.7,
stream=True
):
if hasattr(message.choices[0].delta, 'content'):
response_text += message.choices[0].delta.content
return {
"agent": agent_name,
"role": config["role"],
"response": response_text.strip(),
"status": "success"
}
except Exception as e:
return {
"agent": agent_name,
"role": AGENT_CONFIGS[agent_name]["role"],
"response": f"Error: {str(e)}",
"status": "error"
}
def run_agents_parallel(self, task, selected_agents, max_tokens=300):
"""Run multiple agents in parallel"""
start_time = time.time()
futures = {}
results = []
# Submit tasks to thread pool
for agent_name in selected_agents:
future = self.executor.submit(
self.generate_response,
agent_name,
task,
max_tokens
)
futures[future] = agent_name
# Collect results as they complete
for future in as_completed(futures):
agent_name = futures[future]
try:
result = future.result(timeout=30) # 30 second timeout per agent
result["time_taken"] = round(time.time() - start_time, 2)
results.append(result)
except Exception as e:
results.append({
"agent": agent_name,
"role": AGENT_CONFIGS[agent_name]["role"],
"response": f"Timeout or error: {str(e)}",
"status": "error",
"time_taken": round(time.time() - start_time, 2)
})
total_time = round(time.time() - start_time, 2)
return results, total_time
# Initialize the agent system
print("π Initializing AI Agent System...")
agent_system = AgentSystem()
print("β
System ready!")
def process_task(task, researcher, coder, analyzer, writer, max_tokens, progress=gr.Progress()):
"""Process task with selected agents"""
if not task.strip():
return "β οΈ Please enter a task!", "", ""
# Determine which agents to use
selected_agents = []
if researcher:
selected_agents.append("researcher")
if coder:
selected_agents.append("coder")
if analyzer:
selected_agents.append("analyzer")
if writer:
selected_agents.append("writer")
if not selected_agents:
return "β οΈ Please select at least one agent!", "", ""
progress(0, desc="Starting agents...")
# Run agents in parallel
results, total_time = agent_system.run_agents_parallel(task, selected_agents, max_tokens)
progress(1, desc="Complete!")
# Format output
output = f"# π€ AI Agent System Results\n\n"
output += f"**Task:** {task}\n\n"
output += f"**Agents Used:** {len(selected_agents)} agents running in parallel\n\n"
output += f"**Total Time:** {total_time}s\n\n"
output += "---\n\n"
for idx, result in enumerate(results, 1):
status_emoji = "β
" if result["status"] == "success" else "β"
output += f"## {status_emoji} Agent {idx}: {result['agent'].upper()}\n\n"
output += f"**Role:** {result['role']}\n\n"
output += f"**Response:**\n\n{result['response']}\n\n"
output += f"*β±οΈ Completed in {result['time_taken']}s*\n\n"
output += "---\n\n"
# Create summary stats
success_count = sum(1 for r in results if r["status"] == "success")
stats = f"""π **Execution Stats**
- Total Agents: {len(selected_agents)}
- Successful: {success_count}
- Failed: {len(selected_agents) - success_count}
- Total Time: {total_time}s
- Average per Agent: {round(total_time / len(selected_agents), 2)}s
"""
# Detailed JSON for download
details = {
"task": task,
"agents_used": selected_agents,
"total_time": total_time,
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"results": results
}
import json
json_output = json.dumps(details, indent=2)
return output, stats, json_output
# Create Gradio Interface
custom_css = """
.gradio-container {
font-family: 'Inter', sans-serif;
}
.main-header {
text-align: center;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 10px;
margin-bottom: 20px;
}
"""
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="AI Agent System") as demo:
gr.HTML("""
<div class="main-header">
<h1>π€ Multi-Agent AI System</h1>
<p>Parallel AI Processing with Specialized Agents | Powered by Hugging Face Inference API</p>
</div>
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### π Task Configuration")
task_input = gr.Textbox(
label="What do you want the agents to work on?",
placeholder="Example: Build a user authentication system with JWT tokens",
lines=5
)
gr.Markdown("### π― Select Your Team")
with gr.Group():
researcher_check = gr.Checkbox(
label="π Researcher Agent",
value=True,
info="Gathers information and best practices"
)
coder_check = gr.Checkbox(
label="π» Coder Agent",
value=True,
info="Writes production-ready code"
)
analyzer_check = gr.Checkbox(
label="π Analyzer Agent",
value=True,
info="Provides insights and recommendations"
)
writer_check = gr.Checkbox(
label="βοΈ Writer Agent",
value=True,
info="Creates documentation"
)
gr.Markdown("### βοΈ Settings")
max_tokens = gr.Slider(
minimum=100,
maximum=500,
value=300,
step=50,
label="Response Length",
info="Tokens per agent response"
)
process_btn = gr.Button(
"π Deploy Agents",
variant="primary",
size="lg"
)
gr.Markdown("""
### π‘ Pro Tips
- Use all 4 agents for comprehensive results
- Agents run simultaneously = 3-4x faster!
- Each agent brings unique expertise
- No model downloads = instant startup
""")
with gr.Column(scale=2):
gr.Markdown("### π Results Dashboard")
output_display = gr.Markdown(
value="*Results will appear here after running agents...*",
label="Agent Outputs"
)
with gr.Accordion("π Execution Statistics", open=True):
stats_display = gr.Markdown(value="*No data yet*")
with gr.Accordion("πΎ Download Results (JSON)", open=False):
json_output = gr.Code(
label="Complete Results",
language="json",
lines=10
)
gr.Markdown("### π Quick Start Examples")
gr.Examples(
examples=[
["Create a REST API for a todo list application with authentication"],
["Build a machine learning pipeline for image classification"],
["Design a microservices architecture for an e-commerce platform"],
["Develop a real-time chat application using WebSockets"],
["Create a data visualization dashboard for sales analytics"],
],
inputs=task_input
)
gr.Markdown("""
---
## ποΈ System Architecture
**How It Works:**
1. **Task Distribution** β Your task is sent to selected agents
2. **Parallel Processing** β All agents work simultaneously (not sequential!)
3. **Smart Aggregation** β Results are collected as they complete
4. **Instant Results** β See output from each agent in real-time
**Technology:**
- β‘ Hugging Face Inference API (serverless, no model loading)
- π ThreadPoolExecutor for true parallelism
- π Free tier compatible
- π Real-time progress tracking
**Models Used:**
- Mistral-7B-Instruct (Researcher, Analyzer, Writer)
- StarCoder2-15B (Coder)
""")
# Connect button
process_btn.click(
fn=process_task,
inputs=[
task_input,
researcher_check,
coder_check,
analyzer_check,
writer_check,
max_tokens
],
outputs=[output_display, stats_display, json_output]
)
# Launch with optimized settings
if __name__ == "__main__":
demo.queue(max_size=20) # Handle multiple users
demo.launch(
show_error=True,
share=False
) |