askrobots / dbbasic Public

Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.

0 downloads

dbbasic/dbbasic_ai_service_builder.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add DBBasic crate engine logo and update README 0d628db 1 year, 2 months ago History
dbbasic_ai_service_builder.py · 76.0 KB · 2180 lines
1#!/usr/bin/env python3
2"""
3DBBasic AI Service Builder
4Generate web services from natural language descriptions
5"""
6
7import os
8import json
9import yaml
10import asyncio
11from pathlib import Path
12from typing import Dict, Any, Optional, List
13from dataclasses import dataclass, asdict
14from datetime import datetime
15import textwrap
16import subprocess
17import sys
18
19from presentation_layer import PresentationLayer
20from bootstrap_components import ExtendedBootstrapRenderer
21from dbbasic_unified_ui import get_master_layout, SERVICES
22
23# Initialize presentation layer
24PresentationLayer.add_renderer('bootstrap', ExtendedBootstrapRenderer())
25
26
27from fastapi import FastAPI, HTTPException, Request
28from fastapi.responses import JSONResponse, HTMLResponse
29from fastapi.staticfiles import StaticFiles
30from fastapi.middleware.cors import CORSMiddleware
31from pydantic import BaseModel
32import uvicorn
33import websockets
34import time
35
36# Service generation templates
37SERVICE_TEMPLATE = '''
38#!/usr/bin/env python3
39"""
40AI-Generated Service: {name}
41Description: {description}
42Generated: {timestamp}
43"""
44
45from typing import Dict, Any, Optional
46import json
47import asyncio
48from datetime import datetime
49
50# AI-Generated Implementation
51async def {function_name}(data: Dict[str, Any]) -> Dict[str, Any]:
52 """
53 {description}
54
55 Inputs: {inputs}
56 Outputs: {outputs}
57 """
58
59 try:
60 # Extract inputs
61{input_extraction}
62
63 # AI-Generated Business Logic
64{business_logic}
65
66 # Return results
67 return {{
68 "success": True,
69 "timestamp": datetime.now().isoformat(),
70 "data": result
71 }}
72
73 except Exception as e:
74 return {{
75 "success": False,
76 "error": str(e),
77 "timestamp": datetime.now().isoformat()
78 }}
79
80# Synchronous wrapper for compatibility
81def {function_name}_sync(data: Dict[str, Any]) -> Dict[str, Any]:
82 """Synchronous wrapper for the async function"""
83 return asyncio.run({function_name}(data))
84
85# Export the service
86__all__ = ['{function_name}', '{function_name}_sync']
87'''
88
89class ServiceRequest(BaseModel):
90 """Request to create a new AI service"""
91 name: str
92 description: str
93 inputs: List[str]
94 outputs: List[str]
95 examples: Optional[Dict] = None
96 business_rules: Optional[str] = None
97
98@dataclass
99class AIService:
100 """Represents an AI-generated service"""
101 name: str
102 description: str
103 endpoint: str
104 inputs: List[str]
105 outputs: List[str]
106 status: str # 'generating', 'active', 'error'
107 created_at: datetime
108 code_path: Optional[str] = None
109 error: Optional[str] = None
110 metrics: Optional[Dict] = None
111
112class AIServiceGenerator:
113 """Generates executable services from natural language descriptions"""
114
115 def __init__(self, services_dir: str = "services"):
116 self.services_dir = Path(services_dir)
117 self.services_dir.mkdir(exist_ok=True)
118 self.tests_dir = Path("tests")
119 self.tests_dir.mkdir(exist_ok=True)
120 self.services = {}
121 self.load_existing_services()
122
123 def load_existing_services(self):
124 """Load existing services from directory"""
125 for service_file in self.services_dir.glob("*.py"):
126 if service_file.stem.startswith("_"):
127 continue
128 try:
129 # Read service metadata from file comments
130 with open(service_file, 'r') as f:
131 content = f.read()
132 if 'AI-Generated Service:' in content:
133 name = service_file.stem
134 self.services[name] = AIService(
135 name=name,
136 description="Loaded from file",
137 endpoint=f"/ai/{name}",
138 inputs=[],
139 outputs=[],
140 status="active",
141 created_at=datetime.fromtimestamp(service_file.stat().st_mtime),
142 code_path=str(service_file)
143 )
144 except Exception as e:
145 print(f"Error loading service {service_file}: {e}")
146
147 def generate_test_cases(self, request: ServiceRequest) -> str:
148 """Generate test cases for the service"""
149 function_name = request.name.replace('-', '_')
150 class_name = ''.join(word.capitalize() for word in function_name.split('_'))
151
152 # Generate basic test input based on service type
153 description_lower = request.description.lower()
154
155 if 'shipping' in description_lower:
156 test_input_basic = """{"weight": 2.5, "shipping_speed": "standard", "is_fragile": False, "order_total": 75}"""
157 edge_test_cases = ''' {"weight": 0.1, "shipping_speed": "express", "is_fragile": True, "order_total": 150},
158 {"weight": 10.0, "shipping_speed": "overnight", "is_fragile": False, "order_total": 50},
159 {"weight": 5.0, "shipping_speed": "standard", "is_fragile": True, "order_total": 25}'''
160 elif 'tax' in description_lower or 'discount' in description_lower:
161 test_input_basic = """{"amount": 100.0, "customer_type": "regular", "location": "CA"}"""
162 edge_test_cases = ''' {"amount": 0.01, "customer_type": "premium", "location": "NY"},
163 {"amount": 1000.0, "customer_type": "regular", "location": "TX"},
164 {"amount": 500.0, "customer_type": "vip", "location": "FL"}'''
165 elif 'email' in description_lower or 'notification' in description_lower:
166 test_input_basic = """{"email": "test@example.com", "subject": "Test", "message": "Hello"}"""
167 edge_test_cases = ''' {"email": "user@domain.co.uk", "subject": "", "message": "Short"},
168 {"email": "long.email.address@very-long-domain-name.com", "subject": "Very long subject line", "message": "A" * 1000}'''
169 else:
170 # Generic test case
171 inputs = request.inputs if request.inputs else ['input_value']
172 test_input_basic = "{" + ", ".join([f'"{inp}": "test_value"' for inp in inputs]) + "}"
173 edge_test_cases = ''' {"test_input": "edge_case_1"},
174 {"test_input": "edge_case_2"}'''
175
176 return f'''
177#!/usr/bin/env python3
178"""
179AI-Generated Tests for Service: {request.name}
180Description: {request.description}
181Generated: {datetime.now().isoformat()}
182"""
183
184import pytest
185import asyncio
186import sys
187from pathlib import Path
188
189# Add services directory to path
190sys.path.insert(0, str(Path(__file__).parent.parent / "services"))
191
192from {function_name} import {function_name}, {function_name}_sync
193
194class Test{class_name}:
195 """Test cases for {function_name} service"""
196
197 def test_basic_functionality_sync(self):
198 """Test basic functionality with synchronous wrapper"""
199 test_data = {test_input_basic}
200 result = {function_name}_sync(test_data)
201
202 assert result["success"] is True
203 assert "data" in result
204 assert "timestamp" in result
205
206 @pytest.mark.asyncio
207 async def test_basic_functionality_async(self):
208 """Test basic functionality with async function"""
209 test_data = {test_input_basic}
210 result = await {function_name}(test_data)
211
212 assert result["success"] is True
213 assert "data" in result
214 assert "timestamp" in result
215
216 def test_invalid_input(self):
217 """Test handling of invalid input"""
218 test_data = {{}} # Empty input
219 result = {function_name}_sync(test_data)
220
221 # Should either succeed with defaults or return error
222 assert "success" in result
223 assert "timestamp" in result
224
225 def test_edge_cases(self):
226 """Test edge case scenarios"""
227 edge_cases = [
228{edge_test_cases}
229 ]
230
231 for test_data in edge_cases:
232 result = {function_name}_sync(test_data)
233 assert "success" in result
234 assert "timestamp" in result
235
236 @pytest.mark.asyncio
237 async def test_error_handling(self):
238 """Test error handling with malformed data"""
239 malformed_data = {{"invalid": "data", "nested": {{"bad": None}}}}
240 result = await {function_name}(malformed_data)
241
242 # Should gracefully handle errors
243 assert "success" in result
244 assert "timestamp" in result
245
246if __name__ == "__main__":
247 # Run tests directly
248 pytest.main([__file__, "-v"])
249'''
250
251 def generate_business_logic(self, request: ServiceRequest) -> str:
252 """Generate business logic from description"""
253
254 # This is where AI would generate the actual logic
255 # For now, we'll create intelligent templates based on common patterns
256
257 logic_lines = []
258
259 # Detect common patterns and generate appropriate logic
260 description_lower = request.description.lower()
261
262 if 'calculate' in description_lower or 'compute' in description_lower:
263 # Calculation pattern
264 if 'shipping' in description_lower:
265 logic_lines.extend([
266 "# Calculate shipping cost",
267 "base_cost = weight * 2.5 # $2.50 per pound",
268 "",
269 "# Apply shipping speed multiplier",
270 "speed_multipliers = {",
271 " 'standard': 1.0,",
272 " 'express': 1.5,",
273 " 'overnight': 2.5",
274 "}",
275 "multiplier = speed_multipliers.get(shipping_speed, 1.0)",
276 "cost = base_cost * multiplier",
277 "",
278 "# Add handling fees",
279 "if is_fragile:",
280 " cost += 5.0 # Fragile handling fee",
281 "",
282 "# Check for free shipping",
283 "free_shipping = False",
284 "if 'order_total' in locals() and order_total >= 100:",
285 " cost = 0",
286 " free_shipping = True",
287 "",
288 "result = {",
289 " 'shipping_cost': round(cost, 2),",
290 " 'free_shipping_applied': free_shipping,",
291 " 'carrier': 'UPS' if shipping_speed == 'express' else 'USPS',",
292 " 'estimated_days': 1 if shipping_speed == 'overnight' else (2 if shipping_speed == 'express' else 5)",
293 "}"
294 ])
295 elif 'tax' in description_lower:
296 logic_lines.extend([
297 "# Calculate tax based on location",
298 "tax_rates = {",
299 " 'CA': 0.0725,",
300 " 'NY': 0.08,",
301 " 'TX': 0.0625,",
302 " 'FL': 0.06,",
303 " 'WA': 0.065",
304 "}",
305 "",
306 "state = location.get('state', '') if isinstance(location, dict) else location",
307 "rate = tax_rates.get(state, 0.05) # Default 5% tax",
308 "tax_amount = subtotal * rate",
309 "",
310 "result = {",
311 " 'subtotal': subtotal,",
312 " 'tax_rate': rate,",
313 " 'tax_amount': round(tax_amount, 2),",
314 " 'total': round(subtotal + tax_amount, 2)",
315 "}"
316 ])
317 elif 'discount' in description_lower:
318 logic_lines.extend([
319 "# Calculate discount based on rules",
320 "discount_amount = 0",
321 "discount_reason = []",
322 "",
323 "# Loyalty discount",
324 "if customer_type == 'premium':",
325 " discount_amount += order_total * 0.1",
326 " discount_reason.append('10% premium member discount')",
327 "",
328 "# Volume discount",
329 "if quantity >= 10:",
330 " discount_amount += order_total * 0.05",
331 " discount_reason.append('5% bulk discount')",
332 "",
333 "result = {",
334 " 'original_total': order_total,",
335 " 'discount_amount': round(discount_amount, 2),",
336 " 'final_total': round(order_total - discount_amount, 2),",
337 " 'discount_reasons': discount_reason",
338 "}"
339 ])
340 else:
341 # Generic calculation
342 logic_lines.extend([
343 "# Perform calculation",
344 "result = {}",
345 "for output in " + str(request.outputs) + ":",
346 " result[output] = 0 # AI would calculate actual values"
347 ])
348
349 elif 'validate' in description_lower or 'check' in description_lower:
350 # Validation pattern
351 logic_lines.extend([
352 "# Perform validation",
353 "errors = []",
354 "warnings = []",
355 "",
356 "# AI-generated validation rules",
357 "if 'email' in locals() and '@' not in str(email):",
358 " errors.append('Invalid email format')",
359 "",
360 "if 'phone' in locals() and len(str(phone).replace('-', '')) < 10:",
361 " warnings.append('Phone number may be incomplete')",
362 "",
363 "result = {",
364 " 'valid': len(errors) == 0,",
365 " 'errors': errors,",
366 " 'warnings': warnings",
367 "}"
368 ])
369
370 elif 'send' in description_lower or 'notify' in description_lower:
371 # Notification pattern
372 logic_lines.extend([
373 "# Prepare notification",
374 "import hashlib",
375 "notification_id = hashlib.md5(f'{datetime.now().isoformat()}'.encode()).hexdigest()[:8]",
376 "",
377 "result = {",
378 " 'notification_id': notification_id,",
379 " 'status': 'queued',",
380 " 'recipient': recipient if 'recipient' in locals() else 'default@example.com',",
381 " 'message': message if 'message' in locals() else 'Notification sent',",
382 " 'scheduled_at': datetime.now().isoformat()",
383 "}"
384 ])
385
386 elif 'classify' in description_lower or 'categorize' in description_lower:
387 # Classification pattern
388 logic_lines.extend([
389 "# Perform classification",
390 "# AI would use ML model here",
391 "import random",
392 "",
393 "categories = ['high', 'medium', 'low']",
394 "confidence = round(random.uniform(0.7, 0.99), 2)",
395 "",
396 "result = {",
397 " 'category': random.choice(categories),",
398 " 'confidence': confidence,",
399 " 'reasoning': 'AI-based classification'",
400 "}"
401 ])
402
403 else:
404 # Generic service
405 logic_lines.extend([
406 "# AI-generated business logic",
407 "result = {}",
408 "",
409 "# Process inputs and generate outputs",
410 "for output in " + str(request.outputs) + ":",
411 " # AI would generate actual logic here",
412 " result[output] = f'Generated {output}'"
413 ])
414
415 return "\n ".join(logic_lines)
416
417 def generate_input_extraction(self, inputs: List[str]) -> str:
418 """Generate input extraction code"""
419 lines = []
420 for input_name in inputs:
421 # Infer type from name
422 default = "None"
423 if 'id' in input_name or 'count' in input_name or 'quantity' in input_name:
424 default = "0"
425 elif 'flag' in input_name or 'is_' in input_name:
426 default = "False"
427 elif 'name' in input_name or 'email' in input_name:
428 default = "''"
429 elif 'list' in input_name or 'items' in input_name:
430 default = "[]"
431
432 lines.append(f" {input_name} = data.get('{input_name}', {default})")
433
434 return "\n".join(lines)
435
436 async def generate_service(self, request: ServiceRequest) -> AIService:
437 """Generate a complete AI service from description"""
438
439 # Create service object
440 service = AIService(
441 name=request.name,
442 description=request.description,
443 endpoint=f"/ai/{request.name}",
444 inputs=request.inputs,
445 outputs=request.outputs,
446 status="generating",
447 created_at=datetime.now()
448 )
449
450 self.services[request.name] = service
451
452 # Send task creation event to monitor
453 if monitor.connected:
454 await monitor.send_event("task_created", {
455 "task_type": "service_generation",
456 "service_name": request.name,
457 "description": request.description,
458 "inputs": request.inputs,
459 "outputs": request.outputs
460 })
461
462 try:
463 # Generate the service code
464 function_name = request.name.replace('-', '_')
465
466 code = SERVICE_TEMPLATE.format(
467 name=request.name,
468 function_name=function_name,
469 description=request.description,
470 timestamp=datetime.now().isoformat(),
471 inputs=', '.join(request.inputs),
472 outputs=', '.join(request.outputs),
473 input_extraction=self.generate_input_extraction(request.inputs),
474 business_logic=self.generate_business_logic(request)
475 )
476
477 # Save the service to file
478 service_path = self.services_dir / f"{function_name}.py"
479 with open(service_path, 'w') as f:
480 f.write(code)
481
482 # Send file creation event to monitor
483 if monitor.connected:
484 await monitor.send_event("file_created", {
485 "file_type": "service",
486 "file_path": str(service_path),
487 "service_name": request.name
488 })
489
490 # Generate and save tests
491 test_code = self.generate_test_cases(request)
492 test_path = self.tests_dir / f"test_{function_name}.py"
493 with open(test_path, 'w') as f:
494 f.write(test_code)
495
496 # Send test creation event to monitor
497 if monitor.connected:
498 await monitor.send_event("test_created", {
499 "test_file": str(test_path),
500 "service_name": request.name,
501 "auto_run": True
502 })
503
504 service.code_path = str(service_path)
505 service.test_path = str(test_path)
506 service.status = "active"
507
508 # Initialize metrics
509 service.metrics = {
510 "requests": 0,
511 "errors": 0,
512 "avg_response_time_ms": 0
513 }
514
515 # Automatically run tests for the new service
516 await self.auto_run_service_tests(request.name, service)
517
518 except Exception as e:
519 service.status = "error"
520 service.error = str(e)
521
522 # Send error event to monitor
523 if monitor.connected:
524 await monitor.send_event("task_error", {
525 "task_type": "service_generation",
526 "service_name": request.name,
527 "error": str(e)
528 })
529
530 return service
531
532 async def auto_run_service_tests(self, service_name: str, service: AIService):
533 """Automatically run tests for a newly created service"""
534 try:
535 # Send test start event to monitor
536 if monitor.connected:
537 await monitor.send_event("auto_test_started", {
538 "service_name": service_name,
539 "test_file": service.test_path
540 })
541
542 # Run pytest on the specific test file
543 import subprocess
544 result = subprocess.run(
545 ["python", "-m", "pytest", service.test_path, "-v", "--tb=short"],
546 capture_output=True,
547 text=True,
548 timeout=30
549 )
550
551 test_passed = result.returncode == 0
552
553 # Send test results to monitor
554 if monitor.connected:
555 await monitor.send_event("auto_test_completed", {
556 "service_name": service_name,
557 "test_file": service.test_path,
558 "passed": test_passed,
559 "output": result.stdout,
560 "errors": result.stderr,
561 "exit_code": result.returncode
562 })
563
564 # Update service metrics with test results
565 if service.metrics:
566 service.metrics["last_test_run"] = datetime.now().isoformat()
567 service.metrics["last_test_passed"] = test_passed
568
569 except subprocess.TimeoutExpired:
570 if monitor.connected:
571 await monitor.send_event("auto_test_timeout", {
572 "service_name": service_name,
573 "test_file": service.test_path
574 })
575 except Exception as e:
576 if monitor.connected:
577 await monitor.send_event("auto_test_error", {
578 "service_name": service_name,
579 "error": str(e)
580 })
581
582 async def test_service(self, name: str, test_data: Dict) -> Dict:
583 """Test a service with sample data"""
584
585 service = self.services.get(name)
586 if not service:
587 raise ValueError(f"Service {name} not found")
588
589 if service.status != "active":
590 raise ValueError(f"Service {name} is not active")
591
592 # Import and execute the service
593 try:
594 import importlib.util
595 spec = importlib.util.spec_from_file_location(name, service.code_path)
596 module = importlib.util.module_from_spec(spec)
597 spec.loader.exec_module(module)
598
599 # Get the async function directly (we're already in an async context)
600 function_name = name.replace('-', '_')
601 func = getattr(module, function_name)
602 result = await func(test_data)
603
604 # Update metrics
605 if service.metrics:
606 service.metrics["requests"] += 1
607
608 return result
609
610 except Exception as e:
611 if service.metrics:
612 service.metrics["errors"] += 1
613 raise e
614
615# Real-time monitor WebSocket client
616class MonitorClient:
617 def __init__(self):
618 self.ws = None
619 self.connected = False
620
621 async def connect(self):
622 """Connect to Real-time Monitor WebSocket"""
623 try:
624 self.ws = await websockets.connect("ws://localhost:8004/ws")
625 self.connected = True
626 print("✅ Connected to Real-time Monitor")
627 except Exception as e:
628 print(f"⚠️ Could not connect to Real-time Monitor: {e}")
629 self.connected = False
630
631 async def send_event(self, event_type: str, data: dict):
632 """Send event to monitor"""
633 if not self.connected:
634 return
635
636 try:
637 event = {
638 "type": event_type,
639 "service": "AI Service Builder",
640 "timestamp": datetime.now().isoformat(),
641 "data": data
642 }
643 await self.ws.send(json.dumps(event))
644 except Exception as e:
645 print(f"Failed to send event: {e}")
646 self.connected = False
647
648# Create FastAPI app
649app = FastAPI(title="DBBasic AI Service Builder")
650generator = AIServiceGenerator()
651monitor = MonitorClient()
652
653# Add CORS middleware
654app.add_middleware(
655 CORSMiddleware,
656 allow_origins=["*"],
657 allow_methods=["*"],
658 allow_headers=["*"],
659)
660
661# Add request tracking middleware
662@app.middleware("http")
663async def track_requests(request: Request, call_next):
664 """Track all API requests and send to monitor"""
665 start_time = time.time()
666
667 # Send request event to monitor
668 if monitor.connected:
669 await monitor.send_event("api_request", {
670 "method": request.method,
671 "path": str(request.url.path),
672 "client": request.client.host if request.client else "unknown"
673 })
674
675 response = await call_next(request)
676
677 # Calculate processing time
678 process_time = time.time() - start_time
679
680 # Send response event to monitor
681 if monitor.connected:
682 await monitor.send_event("api_response", {
683 "method": request.method,
684 "path": str(request.url.path),
685 "status": response.status_code,
686 "duration_ms": round(process_time * 1000, 2)
687 })
688
689 return response
690
691# Connect to monitor on startup
692@app.on_event("startup")
693async def startup_event():
694 """Connect to Real-time Monitor on startup"""
695 await monitor.connect()
696
697@app.get("/")
698async def root():
699 """Serve the AI Service Builder using presentation layer"""
700 from dbbasic_ai_service_builder_presentation import get_ai_service_main_ui
701
702 ui_data = get_ai_service_main_ui()
703 html_content = PresentationLayer.render(ui_data, "bootstrap")
704
705 return HTMLResponse(content=html_content)
706
707@app.get("/old-root")
708async def old_root():
709 """Serve the old unified DBBasic dashboard"""
710 return HTMLResponse(content="""<!DOCTYPE html>
711<html lang="en">
712<head>
713 <meta charset="UTF-8">
714 <meta name="viewport" content="width=device-width, initial-scale=1.0">
715 <title>DBBasic - AI Service Platform</title>
716 <style>
717 * { margin: 0; padding: 0; box-sizing: border-box; }
718 body {
719 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
720 background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
721 min-height: 100vh;
722 color: white;
723 }
724 .header {
725 text-align: center;
726 padding: 3rem 2rem;
727 }
728 .logo {
729 font-size: 48px;
730 font-weight: bold;
731 margin-bottom: 1rem;
732 text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
733 }
734 .tagline {
735 font-size: 20px;
736 opacity: 0.9;
737 margin-bottom: 2rem;
738 }
739 .services-grid {
740 display: grid;
741 grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
742 gap: 2rem;
743 max-width: 1200px;
744 margin: 0 auto;
745 padding: 0 2rem 3rem;
746 }
747 .service-card {
748 background: rgba(255, 255, 255, 0.1);
749 backdrop-filter: blur(10px);
750 border-radius: 16px;
751 padding: 2rem;
752 text-align: center;
753 transition: transform 0.3s, box-shadow 0.3s;
754 border: 1px solid rgba(255, 255, 255, 0.2);
755 }
756 .service-card:hover {
757 transform: translateY(-5px);
758 box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
759 }
760 .service-icon {
761 font-size: 48px;
762 margin-bottom: 1rem;
763 }
764 .service-title {
765 font-size: 24px;
766 font-weight: 600;
767 margin-bottom: 1rem;
768 }
769 .service-description {
770 font-size: 14px;
771 opacity: 0.8;
772 margin-bottom: 2rem;
773 line-height: 1.5;
774 }
775 .service-link {
776 display: inline-block;
777 padding: 0.75rem 2rem;
778 background: rgba(255, 255, 255, 0.2);
779 color: white;
780 text-decoration: none;
781 border-radius: 8px;
782 font-weight: 600;
783 transition: background 0.3s;
784 }
785 .service-link:hover {
786 background: rgba(255, 255, 255, 0.3);
787 }
788 .footer {
789 text-align: center;
790 padding: 2rem;
791 opacity: 0.7;
792 font-size: 14px;
793 }
794 .status-bar {
795 display: flex;
796 justify-content: center;
797 gap: 2rem;
798 margin-bottom: 2rem;
799 font-size: 14px;
800 }
801 .status-item {
802 background: rgba(255, 255, 255, 0.1);
803 padding: 0.5rem 1rem;
804 border-radius: 20px;
805 }
806 .nav-bar {
807 background: rgba(0, 0, 0, 0.3);
808 backdrop-filter: blur(10px);
809 padding: 1rem 2rem;
810 display: flex;
811 justify-content: space-between;
812 align-items: center;
813 border-bottom: 1px solid rgba(255, 255, 255, 0.1);
814 }
815 .nav-brand {
816 font-size: 18px;
817 font-weight: bold;
818 color: white;
819 }
820 .nav-links {
821 display: flex;
822 gap: 2rem;
823 align-items: center;
824 }
825 .nav-links a {
826 color: rgba(255, 255, 255, 0.8);
827 text-decoration: none;
828 padding: 0.5rem 1rem;
829 border-radius: 4px;
830 transition: all 0.3s;
831 font-size: 14px;
832 border: 1px solid transparent;
833 }
834 .nav-links a:hover {
835 background: rgba(255, 255, 255, 0.1);
836 border-color: rgba(255, 255, 255, 0.3);
837 color: white;
838 }
839 .nav-links a.active {
840 background: rgba(255, 255, 255, 0.2);
841 border-color: rgba(255, 255, 255, 0.5);
842 color: white;
843 }
844 </style>
845</head>
846<body>
847 <div class="nav-bar">
848 <div class="nav-brand">DBBasic</div>
849 <nav class="nav-links">
850 <a href="http://localhost:8004">Monitor</a>
851 <a href="http://localhost:8005">CRUD Engine</a>
852 <a href="http://localhost:8003" class="active">AI Services</a>
853 <a href="http://localhost:8006">Event Store</a>
854 <a href="http://localhost:8000/static/mockups.html">Templates</a>
855 </nav>
856 <div style="color: rgba(255, 255, 255, 0.7); font-size: 14px;">402M rows/sec</div>
857 </div>
858 <div class="header">
859 <div class="logo">DBBasic</div>
860 <div class="tagline">AI Service Platform - Config → Code → Tests</div>
861 <div class="status-bar">
862 <div class="status-item">🚀 402M rows/sec</div>
863 <div class="status-item">⚡ Post-Code Era</div>
864 <div class="status-item">🔗 All Services Connected</div>
865 </div>
866 </div>
867
868 <div class="services-grid">
869 <div class="service-card">
870 <div class="service-icon">🛠️</div>
871 <div class="service-title">Service Builder</div>
872 <div class="service-description">Create AI services from natural language descriptions. Generate code, config, and tests automatically.</div>
873 <a href="/fresh" class="service-link">Build Services</a>
874 </div>
875
876 <div class="service-card">
877 <div class="service-icon">🧪</div>
878 <div class="service-title">Test Runner</div>
879 <div class="service-description">Run comprehensive tests for all generated services. Validate functionality and catch regressions.</div>
880 <a href="/tests" class="service-link">Run Tests</a>
881 </div>
882
883 <div class="service-card">
884 <div class="service-icon">📊</div>
885 <div class="service-title">System Logs</div>
886 <div class="service-description">Monitor service executions, rule applications, and system performance in real-time.</div>
887 <a href="/logs" class="service-link">View Logs</a>
888 </div>
889
890 <div class="service-card">
891 <div class="service-icon">⚙️</div>
892 <div class="service-title">Config Examples</div>
893 <div class="service-description">Explore config-driven services and see how business logic becomes executable YAML.</div>
894 <a href="/config" class="service-link">Browse Configs</a>
895 </div>
896
897 <div class="service-card">
898 <div class="service-icon">📋</div>
899 <div class="service-title">Service Status</div>
900 <div class="service-description">View all active services, their endpoints, and real-time performance metrics.</div>
901 <a href="/api/services" class="service-link">View Services</a>
902 </div>
903
904 <div class="service-card">
905 <div class="service-icon">🔍</div>
906 <div class="service-title">Code Viewer</div>
907 <div class="service-description">Browse generated service code with syntax highlighting and direct endpoint access.</div>
908 <a href="/code" class="service-link">View Code</a>
909 </div>
910 <div class="service-card">
911 <div class="service-icon">📡</div>
912 <div class="service-title">Real-time Monitor</div>
913 <div class="service-description">Watch live service activity with WebSocket updates. See actual service execution in real-time.</div>
914 <a href="http://localhost:8004" class="service-link" target="_blank">Open Monitor →</a>
915 </div>
916 <div class="service-card">
917 <div class="service-icon">✅</div>
918 <div class="service-title">Test Runner Web</div>
919 <div class="service-description">Run tests from your browser and see red/green results with live output streaming.</div>
920 <a href="http://localhost:8006" class="service-link" target="_blank">Open Test Runner →</a>
921 </div>
922 </div>
923
924 <div class="footer">
925 <p><strong>DBBasic v1.0</strong> - The Complete AI Service Platform</p>
926 <p>Natural Language → Business Rules → Working Services</p>
927 <p style="margin-top: 1rem; opacity: 0.8;">Main Dashboard: <a href="http://localhost:8003" style="color: white;">Port 8003</a> | Monitor: <a href="http://localhost:8004" style="color: white;">Port 8004</a> | Tests: <a href="http://localhost:8006" style="color: white;">Port 8006</a></p>
928 </div>
929
930 <script>
931 // Add some interactivity
932 document.querySelectorAll('.service-card').forEach(card => {
933 card.addEventListener('click', (e) => {
934 if (e.target.tagName !== 'A') {
935 const link = card.querySelector('.service-link');
936 if (link) window.location.href = link.href;
937 }
938 });
939 });
940 </script>
941</body>
942</html>""")
943
944@app.get("/fresh")
945async def fresh_interface():
946 """Serve fresh AI Service Builder interface using presentation layer"""
947 from dbbasic_ai_service_builder_presentation import get_ai_service_main_ui
948
949 # Generate the UI using presentation layer
950 ui_data = get_ai_service_main_ui()
951 html_content = PresentationLayer.render(ui_data, 'bootstrap')
952
953 # Add timestamp to force cache invalidation
954 import time
955 timestamp = str(int(time.time()))
956
957 # Inject cache-busting script
958 cache_buster = f"""
959 <script>
960 // Force cache invalidation {timestamp}
961 console.log('Presentation Layer UI loaded at {timestamp}');
962 </script>
963 """
964
965 # Insert before closing head tag
966 html_content = html_content.replace('</head>', cache_buster + '</head>')
967
968 return HTMLResponse(
969 content=html_content,
970 headers={
971 "Cache-Control": "no-cache, no-store, must-revalidate, proxy-revalidate",
972 "Pragma": "no-cache",
973 "Expires": "0",
974 "ETag": f'"{timestamp}"',
975 "Last-Modified": "Wed, 21 Oct 2015 07:28:00 GMT",
976 "Vary": "*"
977 }
978 )
979
980@app.get("/builder")
981async def builder_interface():
982 """Serve working AI Service Builder interface"""
983 html_path = Path("static/ai_service_builder.html")
984 if html_path.exists():
985 content = html_path.read_text()
986 return HTMLResponse(
987 content=content,
988 headers={
989 "Cache-Control": "no-cache, no-store, must-revalidate",
990 "Pragma": "no-cache",
991 "Expires": "0"
992 }
993 )
994 else:
995 return HTMLResponse(content="<h1>Interface not found</h1>")
996
997@app.post("/api/services/create")
998async def create_service(request: ServiceRequest):
999 """Create a new AI service from description"""
1000 try:
1001 service = await generator.generate_service(request)
1002 service_dict = asdict(service)
1003 service_dict['created_at'] = service.created_at.isoformat()
1004 return JSONResponse(content=service_dict, status_code=201)
1005 except Exception as e:
1006 raise HTTPException(status_code=400, detail=str(e))
1007
1008@app.get("/api/services")
1009async def list_services():
1010 """List all available services"""
1011 services = [
1012 {
1013 **asdict(service),
1014 "created_at": service.created_at.isoformat()
1015 }
1016 for service in generator.services.values()
1017 ]
1018 return JSONResponse(content=services)
1019
1020@app.get("/api/services/{name}")
1021async def get_service(name: str):
1022 """Get details of a specific service"""
1023 service = generator.services.get(name)
1024 if not service:
1025 raise HTTPException(status_code=404, detail=f"Service {name} not found")
1026
1027 return JSONResponse(content={
1028 **asdict(service),
1029 "created_at": service.created_at.isoformat()
1030 })
1031
1032@app.post("/api/services/{name}/test")
1033async def test_service(name: str, test_data: Dict[str, Any]):
1034 """Test a service with sample data"""
1035 try:
1036 result = await generator.test_service(name, test_data)
1037 return JSONResponse(content=result)
1038 except Exception as e:
1039 raise HTTPException(status_code=400, detail=str(e))
1040
1041@app.post("/ai/{name}")
1042async def execute_service(name: str, data: Dict[str, Any]):
1043 """Execute an AI service"""
1044 try:
1045 result = await generator.test_service(name, data)
1046 return JSONResponse(content=result)
1047 except Exception as e:
1048 raise HTTPException(status_code=400, detail=str(e))
1049
1050@app.get("/api/services/{name}/code")
1051async def get_service_code(name: str):
1052 """Get the generated code for a service"""
1053 service = generator.services.get(name)
1054 if not service or not service.code_path:
1055 raise HTTPException(status_code=404, detail=f"Service code not found")
1056
1057 try:
1058 with open(service.code_path, 'r') as f:
1059 code = f.read()
1060 return JSONResponse(content={"code": code, "language": "python"})
1061 except Exception as e:
1062 raise HTTPException(status_code=500, detail=str(e))
1063
1064@app.get("/code/{name}")
1065async def view_service_code(name: str):
1066 """View service code directly in browser"""
1067 service = generator.services.get(name)
1068 if not service or not service.code_path:
1069 return HTMLResponse(content="<h1>Service not found</h1>")
1070
1071 try:
1072 with open(service.code_path, 'r') as f:
1073 code = f.read()
1074
1075 # Escape HTML
1076 code = code.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
1077
1078 html = f"""<!DOCTYPE html>
1079<html>
1080<head>
1081 <title>Code: {name}</title>
1082 <style>
1083 body {{ font-family: monospace; margin: 20px; background: #1e1e1e; color: #d4d4d4; }}
1084 pre {{ background: #2d2d2d; padding: 20px; border-radius: 8px; overflow-x: auto; }}
1085 h1 {{ color: #fff; }}
1086 .back {{ color: #4fc3f7; text-decoration: none; }}
1087 </style>
1088</head>
1089<body>
1090 <h1>Generated Code: {name}</h1>
1091 <a href="/fresh" class="back">← Back to AI Service Builder</a>
1092 <pre>{code}</pre>
1093</body>
1094</html>"""
1095 return HTMLResponse(content=html)
1096 except Exception as e:
1097 return HTMLResponse(content=f"<h1>Error loading code: {e}</h1>")
1098
1099# Mount static files if directory exists
1100static_dir = Path("static")
1101if static_dir.exists():
1102 app.mount("/static", StaticFiles(directory="static"), name="static")
1103
1104@app.get("/api/logs")
1105async def get_logs(limit: int = 100, level: str = "all"):
1106 """Get application logs - foundation for DBBasic monitoring/Sentry"""
1107 import glob
1108 import os
1109 from datetime import datetime
1110
1111 logs = []
1112
1113 # Collect uvicorn access logs (recent requests)
1114 try:
1115 # Get recent background bash outputs for live logs
1116 bash_outputs = []
1117 for bash_id in ["25aad2", "08dd66", "6bd043", "e94b16"]: # Recent bash instances
1118 try:
1119 # This would need BashOutput access in real implementation
1120 # For now, simulate with recent activity
1121 pass
1122 except:
1123 pass
1124
1125 # Read any log files in the directory
1126 log_files = glob.glob("*.log") + glob.glob("logs/*.log")
1127 for log_file in log_files:
1128 try:
1129 with open(log_file, 'r') as f:
1130 lines = f.readlines()[-50:] # Last 50 lines
1131 for line in lines:
1132 logs.append({
1133 "timestamp": datetime.now().isoformat(),
1134 "level": "info",
1135 "source": log_file,
1136 "message": line.strip()
1137 })
1138 except:
1139 pass
1140
1141 # Add service activity logs
1142 for service_name in generator.services:
1143 service = generator.services[service_name]
1144 logs.append({
1145 "timestamp": service.created_at.isoformat(),
1146 "level": "info",
1147 "source": f"service:{service_name}",
1148 "message": f"Service {service_name} created and active",
1149 "endpoint": service.endpoint
1150 })
1151
1152 # Add recent API activity (simulated from our knowledge)
1153 recent_activity = [
1154 {"endpoint": "/api/services", "method": "GET", "status": 200, "count": 15},
1155 {"endpoint": "/api/services/calculate_shipping/code", "method": "GET", "status": 200, "count": 8},
1156 {"endpoint": "/fresh", "method": "GET", "status": 200, "count": 3},
1157 {"endpoint": "/api/services/calculate_discount/code", "method": "GET", "status": 200, "count": 2}
1158 ]
1159
1160 for activity in recent_activity:
1161 logs.append({
1162 "timestamp": datetime.now().isoformat(),
1163 "level": "info",
1164 "source": "api",
1165 "message": f"{activity['method']} {activity['endpoint']} - {activity['status']} ({activity['count']} requests)",
1166 "endpoint": activity["endpoint"],
1167 "method": activity["method"],
1168 "status_code": activity["status"],
1169 "request_count": activity["count"]
1170 })
1171
1172 except Exception as e:
1173 logs.append({
1174 "timestamp": datetime.now().isoformat(),
1175 "level": "error",
1176 "source": "log_collector",
1177 "message": f"Error collecting logs: {str(e)}"
1178 })
1179
1180 # Filter by level if specified
1181 if level != "all":
1182 logs = [log for log in logs if log.get("level", "info") == level]
1183
1184 # Sort by timestamp and limit
1185 logs.sort(key=lambda x: x["timestamp"], reverse=True)
1186 logs = logs[:limit]
1187
1188 return {
1189 "logs": logs,
1190 "total": len(logs),
1191 "filters": {
1192 "level": level,
1193 "limit": limit
1194 },
1195 "system_info": {
1196 "active_services": len(generator.services),
1197 "server_status": "running",
1198 "uptime": "running" # Could calculate actual uptime
1199 }
1200 }
1201
1202@app.get("/logs")
1203async def logs_interface():
1204 """Web interface for viewing logs"""
1205 html_content = '''<!DOCTYPE html>
1206<html lang="en">
1207<head>
1208 <meta charset="UTF-8">
1209 <meta name="viewport" content="width=device-width, initial-scale=1.0">
1210 <title>DBBasic - System Logs</title>
1211 <style>
1212 * { margin: 0; padding: 0; box-sizing: border-box; }
1213 body {
1214 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1215 background: #f5f5f5;
1216 height: 100vh;
1217 display: flex;
1218 flex-direction: column;
1219 }
1220 .header {
1221 background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1222 color: white;
1223 padding: 1rem 2rem;
1224 display: flex;
1225 justify-content: space-between;
1226 align-items: center;
1227 }
1228 .logo { font-size: 24px; font-weight: bold; }
1229 .subtitle { font-size: 14px; opacity: 0.9; }
1230 .container {
1231 flex: 1;
1232 padding: 2rem;
1233 overflow-y: auto;
1234 }
1235 .controls {
1236 background: white;
1237 padding: 1rem;
1238 border-radius: 8px;
1239 margin-bottom: 1rem;
1240 display: flex;
1241 gap: 1rem;
1242 align-items: center;
1243 }
1244 .log-container {
1245 background: #1e1e1e;
1246 color: #d4d4d4;
1247 border-radius: 8px;
1248 padding: 1rem;
1249 font-family: monospace;
1250 font-size: 13px;
1251 max-height: 70vh;
1252 overflow-y: auto;
1253 }
1254 .log-entry {
1255 margin-bottom: 0.5rem;
1256 padding: 0.5rem;
1257 border-radius: 4px;
1258 border-left: 3px solid #333;
1259 }
1260 .log-info { border-left-color: #4CAF50; }
1261 .log-error { border-left-color: #f44336; background: rgba(244, 67, 54, 0.1); }
1262 .log-warning { border-left-color: #ff9800; background: rgba(255, 152, 0, 0.1); }
1263 .timestamp { color: #888; font-size: 11px; }
1264 .source { color: #64B5F6; font-weight: bold; }
1265 .message { margin-top: 0.25rem; }
1266 .refresh-btn {
1267 background: #667eea;
1268 color: white;
1269 border: none;
1270 padding: 0.5rem 1rem;
1271 border-radius: 4px;
1272 cursor: pointer;
1273 }
1274 .stats {
1275 display: grid;
1276 grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
1277 gap: 1rem;
1278 margin-bottom: 1rem;
1279 }
1280 .stat-card {
1281 background: white;
1282 padding: 1rem;
1283 border-radius: 8px;
1284 text-align: center;
1285 }
1286 .stat-value { font-size: 24px; font-weight: bold; color: #667eea; }
1287 .stat-label { font-size: 12px; color: #666; margin-top: 0.25rem; }
1288 </style>
1289</head>
1290<body>
1291 <div class="header">
1292 <div>
1293 <div class="logo">DBBasic</div>
1294 <div class="subtitle">System Logs & Monitoring</div>
1295 </div>
1296 <div>
1297 <span id="status">🟢 System Online</span>
1298 </div>
1299 </div>
1300
1301 <div class="container">
1302 <div class="stats">
1303 <div class="stat-card">
1304 <div class="stat-value" id="activeServices">-</div>
1305 <div class="stat-label">Active Services</div>
1306 </div>
1307 <div class="stat-card">
1308 <div class="stat-value" id="totalLogs">-</div>
1309 <div class="stat-label">Log Entries</div>
1310 </div>
1311 <div class="stat-card">
1312 <div class="stat-value" id="errorCount">-</div>
1313 <div class="stat-label">Errors</div>
1314 </div>
1315 </div>
1316
1317 <div class="controls">
1318 <button class="refresh-btn" onclick="loadLogs()">🔄 Refresh</button>
1319 <select id="levelFilter" onchange="loadLogs()">
1320 <option value="all">All Levels</option>
1321 <option value="info">Info</option>
1322 <option value="error">Errors</option>
1323 <option value="warning">Warnings</option>
1324 </select>
1325 <label>Auto-refresh: <input type="checkbox" id="autoRefresh" onchange="toggleAutoRefresh()"></label>
1326 </div>
1327
1328 <div class="log-container" id="logs">
1329 Loading logs...
1330 </div>
1331 </div>
1332
1333 <script>
1334 let autoRefreshInterval = null;
1335
1336 async function loadLogs() {
1337 const level = document.getElementById('levelFilter').value;
1338 try {
1339 const response = await fetch(`/api/logs?level=${level}&limit=100`);
1340 const data = await response.json();
1341
1342 // Update stats
1343 document.getElementById('activeServices').textContent = data.system_info.active_services;
1344 document.getElementById('totalLogs').textContent = data.total;
1345 document.getElementById('errorCount').textContent =
1346 data.logs.filter(log => log.level === 'error').length;
1347
1348 // Render logs
1349 const logsContainer = document.getElementById('logs');
1350 logsContainer.innerHTML = data.logs.map(log => `
1351 <div class="log-entry log-${log.level}">
1352 <div class="timestamp">${new Date(log.timestamp).toLocaleString()}</div>
1353 <div class="source">[${log.source}]</div>
1354 <div class="message">${log.message}</div>
1355 </div>
1356 `).join('');
1357
1358 } catch (error) {
1359 document.getElementById('logs').innerHTML =
1360 `<div class="log-entry log-error">Error loading logs: ${error.message}</div>`;
1361 }
1362 }
1363
1364 function toggleAutoRefresh() {
1365 const checkbox = document.getElementById('autoRefresh');
1366 if (checkbox.checked) {
1367 autoRefreshInterval = setInterval(loadLogs, 5000); // Refresh every 5 seconds
1368 } else {
1369 clearInterval(autoRefreshInterval);
1370 autoRefreshInterval = null;
1371 }
1372 }
1373
1374 // Load logs on page load
1375 loadLogs();
1376 </script>
1377</body>
1378</html>'''
1379
1380 return HTMLResponse(content=html_content)
1381
1382@app.get("/api/tasks/check")
1383async def check_pending_tasks():
1384 """Check for pending tasks and execute them"""
1385 tasks = []
1386
1387 # Check for services with tests that need to be run
1388 for service_name, service in generator.services.items():
1389 if service.status == "active" and hasattr(service, 'test_path'):
1390 # Check if tests have been run recently
1391 last_test_run = service.metrics.get("last_test_run") if service.metrics else None
1392
1393 tasks.append({
1394 "type": "test_execution",
1395 "service_name": service_name,
1396 "test_file": service.test_path,
1397 "last_run": last_test_run,
1398 "needs_testing": last_test_run is None
1399 })
1400
1401 # Send task check event to monitor
1402 if monitor.connected:
1403 await monitor.send_event("task_check_completed", {
1404 "total_tasks": len(tasks),
1405 "pending_tests": sum(1 for t in tasks if t["needs_testing"])
1406 })
1407
1408 return {
1409 "total_tasks": len(tasks),
1410 "tasks": tasks,
1411 "timestamp": datetime.now().isoformat()
1412 }
1413
1414@app.post("/api/tasks/run-pending")
1415async def run_pending_tasks():
1416 """Run all pending tasks (tests for services that haven't been tested)"""
1417 results = []
1418
1419 for service_name, service in generator.services.items():
1420 if service.status == "active" and hasattr(service, 'test_path'):
1421 last_test_run = service.metrics.get("last_test_run") if service.metrics else None
1422
1423 # Run tests if they haven't been run yet
1424 if last_test_run is None:
1425 try:
1426 await generator.auto_run_service_tests(service_name, service)
1427 results.append({
1428 "service": service_name,
1429 "status": "tests_executed",
1430 "test_file": service.test_path
1431 })
1432 except Exception as e:
1433 results.append({
1434 "service": service_name,
1435 "status": "error",
1436 "error": str(e)
1437 })
1438
1439 # Send batch test completion to monitor
1440 if monitor.connected:
1441 await monitor.send_event("batch_tests_completed", {
1442 "total_services": len(results),
1443 "executed_tests": len([r for r in results if r["status"] == "tests_executed"])
1444 })
1445
1446 return {
1447 "executed": len(results),
1448 "results": results,
1449 "timestamp": datetime.now().isoformat()
1450 }
1451
1452@app.get("/api/tests/run")
1453async def run_tests():
1454 """Run all tests and return results"""
1455 import subprocess
1456 import os
1457
1458 try:
1459 # Change to project directory
1460 original_dir = os.getcwd()
1461
1462 # Run pytest on tests directory
1463 result = subprocess.run(
1464 ["python", "-m", "pytest", "tests/", "-v", "--tb=short", "--json-report", "--json-report-file=test_results.json"],
1465 capture_output=True,
1466 text=True,
1467 timeout=60
1468 )
1469
1470 # Try to read JSON results if available
1471 test_results = {
1472 "success": result.returncode == 0,
1473 "exit_code": result.returncode,
1474 "stdout": result.stdout,
1475 "stderr": result.stderr
1476 }
1477
1478 # Parse test results for better presentation
1479 if "PASSED" in result.stdout or "FAILED" in result.stdout:
1480 lines = result.stdout.split('\n')
1481 test_cases = []
1482
1483 for line in lines:
1484 if "::" in line and ("PASSED" in line or "FAILED" in line):
1485 parts = line.split("::")
1486 if len(parts) >= 2:
1487 test_file = parts[0].replace("tests/", "")
1488 test_name = parts[1].split()[0]
1489 status = "PASSED" if "PASSED" in line else "FAILED"
1490 test_cases.append({
1491 "file": test_file,
1492 "name": test_name,
1493 "status": status
1494 })
1495
1496 test_results["test_cases"] = test_cases
1497
1498 return test_results
1499
1500 except subprocess.TimeoutExpired:
1501 return {
1502 "success": False,
1503 "error": "Tests timed out after 60 seconds",
1504 "exit_code": -1
1505 }
1506 except Exception as e:
1507 return {
1508 "success": False,
1509 "error": str(e),
1510 "exit_code": -1
1511 }
1512
1513@app.get("/config")
1514async def config_browser():
1515 """Browse config files showing config-driven development"""
1516 import glob
1517 import yaml
1518 import os
1519
1520 # Get the DBBasic directory path
1521 dbbasic_dir = os.path.dirname(os.path.abspath(__file__))
1522 print(f"DEBUG: Looking for configs in: {dbbasic_dir}")
1523
1524 # Find all YAML config files
1525 config_files = []
1526
1527 # Service configs
1528 pattern1 = os.path.join(dbbasic_dir, "*.yaml")
1529 print(f"DEBUG: Service config pattern: {pattern1}")
1530 service_configs = glob.glob(pattern1)
1531 print(f"DEBUG: Found service configs: {service_configs}")
1532
1533 for file in service_configs:
1534 basename = os.path.basename(file)
1535 config_files.append({
1536 'path': file,
1537 'category': 'Service Configs',
1538 'name': basename.replace('_', ' ').replace('.yaml', '').title()
1539 })
1540
1541 # Paradigm configs showing frameworks as config
1542 pattern2 = os.path.join(dbbasic_dir, "docs/paradigms/*.yaml")
1543 print(f"DEBUG: Paradigm config pattern: {pattern2}")
1544 paradigm_configs = glob.glob(pattern2)
1545 print(f"DEBUG: Found paradigm configs: {paradigm_configs}")
1546
1547 for file in paradigm_configs:
1548 name = os.path.basename(file).replace('_IN_CONFIG.yaml', '')
1549 config_files.append({
1550 'path': file,
1551 'category': 'Frameworks as Config',
1552 'name': name.replace('_', ' ').title()
1553 })
1554
1555 print(f"DEBUG: Total config files: {len(config_files)}")
1556
1557 html_content = '''<!DOCTYPE html>
1558<html lang="en">
1559<head>
1560 <meta charset="UTF-8">
1561 <meta name="viewport" content="width=device-width, initial-scale=1.0">
1562 <title>DBBasic Config Browser - Config = Code</title>
1563 <style>
1564 * { margin: 0; padding: 0; box-sizing: border-box; }
1565 body {
1566 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1567 background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1568 min-height: 100vh;
1569 color: white;
1570 }
1571 .header {
1572 padding: 2rem;
1573 text-align: center;
1574 border-bottom: 1px solid rgba(255,255,255,0.1);
1575 }
1576 .tagline {
1577 font-size: 1.2rem;
1578 opacity: 0.9;
1579 margin-top: 0.5rem;
1580 }
1581 .container {
1582 max-width: 1400px;
1583 margin: 0 auto;
1584 padding: 2rem;
1585 }
1586 .category {
1587 margin-bottom: 3rem;
1588 }
1589 .category-title {
1590 font-size: 1.5rem;
1591 margin-bottom: 1rem;
1592 padding-bottom: 0.5rem;
1593 border-bottom: 2px solid rgba(255,255,255,0.3);
1594 }
1595 .config-grid {
1596 display: grid;
1597 grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
1598 gap: 1rem;
1599 }
1600 .config-card {
1601 background: rgba(255, 255, 255, 0.1);
1602 backdrop-filter: blur(10px);
1603 border-radius: 8px;
1604 padding: 1.5rem;
1605 cursor: pointer;
1606 transition: all 0.3s;
1607 border: 1px solid rgba(255, 255, 255, 0.2);
1608 }
1609 .config-card:hover {
1610 transform: translateY(-2px);
1611 box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
1612 background: rgba(255, 255, 255, 0.15);
1613 }
1614 .config-name {
1615 font-size: 1.1rem;
1616 font-weight: 600;
1617 margin-bottom: 0.5rem;
1618 }
1619 .config-path {
1620 font-size: 0.85rem;
1621 opacity: 0.7;
1622 font-family: monospace;
1623 }
1624 .modal {
1625 display: none;
1626 position: fixed;
1627 top: 0;
1628 left: 0;
1629 width: 100%;
1630 height: 100%;
1631 background: rgba(0, 0, 0, 0.8);
1632 z-index: 1000;
1633 overflow-y: auto;
1634 }
1635 .modal-content {
1636 background: #1e1e1e;
1637 margin: 2rem auto;
1638 padding: 2rem;
1639 max-width: 90%;
1640 border-radius: 12px;
1641 position: relative;
1642 }
1643 .close {
1644 position: absolute;
1645 right: 1rem;
1646 top: 1rem;
1647 font-size: 2rem;
1648 cursor: pointer;
1649 color: white;
1650 }
1651 .config-viewer {
1652 background: #2d2d30;
1653 border-radius: 8px;
1654 padding: 1rem;
1655 overflow-x: auto;
1656 }
1657 .config-viewer pre {
1658 color: #d4d4d4;
1659 font-family: 'Monaco', 'Menlo', monospace;
1660 font-size: 14px;
1661 line-height: 1.6;
1662 }
1663 .insight-box {
1664 background: linear-gradient(135deg, #ff6b6b, #feca57);
1665 padding: 1.5rem;
1666 border-radius: 12px;
1667 margin-bottom: 2rem;
1668 color: white;
1669 }
1670 .insight-title {
1671 font-size: 1.3rem;
1672 font-weight: bold;
1673 margin-bottom: 0.5rem;
1674 }
1675 .insight-text {
1676 font-size: 1.1rem;
1677 }
1678 .nav-link {
1679 display: inline-block;
1680 color: white;
1681 text-decoration: none;
1682 padding: 0.5rem 1rem;
1683 margin-right: 1rem;
1684 background: rgba(255, 255, 255, 0.1);
1685 border-radius: 6px;
1686 transition: background 0.3s;
1687 }
1688 .nav-link:hover {
1689 background: rgba(255, 255, 255, 0.2);
1690 }
1691 </style>
1692</head>
1693<body>
1694 <div class="header">
1695 <h1>🔧 DBBasic Config Browser</h1>
1696 <div class="tagline">Config = Code You Don't Have to Write</div>
1697 <div style="margin-top: 1rem;">
1698 <a href="/" class="nav-link">← Back to Dashboard</a>
1699 <a href="/fresh" class="nav-link">Build Services</a>
1700 <a href="/logs" class="nav-link">View Logs</a>
1701 </div>
1702 </div>
1703
1704 <div class="container">
1705 <div class="insight-box">
1706 <div class="insight-title">💡 The Config Revolution</div>
1707 <div class="insight-text">
1708 Every line of code is a liability. Config is an asset.<br>
1709 These configs show entire frameworks expressed as YAML.<br>
1710 No code → Software with options.
1711 </div>
1712 </div>
1713
1714 <!-- Service Configs -->
1715 <div class="category">
1716 <h2 class="category-title">📦 Service Configs</h2>
1717 <div class="config-grid" id="service-configs"></div>
1718 </div>
1719
1720 <!-- Framework Configs -->
1721 <div class="category">
1722 <h2 class="category-title">🚀 Frameworks as Config</h2>
1723 <div class="config-grid" id="framework-configs"></div>
1724 </div>
1725 </div>
1726
1727 <!-- Modal for viewing config -->
1728 <div id="configModal" class="modal">
1729 <div class="modal-content">
1730 <span class="close">&times;</span>
1731 <h2 id="modalTitle" style="margin-bottom: 1rem;"></h2>
1732 <div class="config-viewer">
1733 <pre id="configContent"></pre>
1734 </div>
1735 </div>
1736 </div>
1737
1738 <script>
1739 document.addEventListener('DOMContentLoaded', () => {
1740 const configs = ''' + json.dumps(config_files) + ''';
1741 console.log('Loaded configs:', configs);
1742
1743 // Group configs by category
1744 const serviceConfigs = configs.filter(c => c.category === 'Service Configs');
1745 const frameworkConfigs = configs.filter(c => c.category === 'Frameworks as Config');
1746
1747 console.log('Service configs:', serviceConfigs.length);
1748 console.log('Framework configs:', frameworkConfigs.length);
1749
1750 // Render service configs
1751 const serviceGrid = document.getElementById('service-configs');
1752 if (!serviceGrid) {
1753 console.error('Could not find service-configs element!');
1754 return;
1755 }
1756 serviceConfigs.forEach(config => {
1757 const card = document.createElement('div');
1758 card.className = 'config-card';
1759 card.innerHTML = `
1760 <div class="config-name">${config.name}</div>
1761 <div class="config-path">${config.path}</div>
1762 `;
1763 card.onclick = () => loadConfig(config);
1764 serviceGrid.appendChild(card);
1765 });
1766
1767 // Render framework configs
1768 const frameworkGrid = document.getElementById('framework-configs');
1769 frameworkConfigs.forEach(config => {
1770 const card = document.createElement('div');
1771 card.className = 'config-card';
1772 card.innerHTML = `
1773 <div class="config-name">${config.name}</div>
1774 <div class="config-path">${config.path.split('/').pop()}</div>
1775 `;
1776 card.onclick = () => loadConfig(config);
1777 frameworkGrid.appendChild(card);
1778 });
1779
1780 // Modal handling
1781 const modal = document.getElementById('configModal');
1782 const modalTitle = document.getElementById('modalTitle');
1783 const configContent = document.getElementById('configContent');
1784 const closeBtn = document.getElementsByClassName('close')[0];
1785
1786 closeBtn.onclick = () => {
1787 modal.style.display = 'none';
1788 };
1789
1790 window.onclick = (event) => {
1791 if (event.target === modal) {
1792 modal.style.display = 'none';
1793 }
1794 };
1795
1796 async function loadConfig(config) {
1797 modalTitle.textContent = config.name;
1798 configContent.textContent = 'Loading...';
1799 modal.style.display = 'block';
1800
1801 try {
1802 const response = await fetch(`/api/config/${encodeURIComponent(config.path)}`);
1803 const data = await response.json();
1804
1805 // Apply syntax highlighting
1806 configContent.innerHTML = syntaxHighlightYAML(data.content);
1807 } catch (error) {
1808 configContent.textContent = 'Error loading config: ' + error.message;
1809 }
1810 }
1811
1812 function syntaxHighlightYAML(yaml) {
1813 // Create a temporary element to safely build HTML
1814 const temp = document.createElement('div');
1815
1816 // Split into lines for processing
1817 const lines = yaml.split('\\n');
1818
1819 lines.forEach(line => {
1820 const lineSpan = document.createElement('span');
1821
1822 // Check for comments
1823 if (line.includes('#')) {
1824 const commentIndex = line.indexOf('#');
1825 const beforeComment = line.substring(0, commentIndex);
1826 const comment = line.substring(commentIndex);
1827
1828 // Add the part before the comment
1829 processLine(lineSpan, beforeComment);
1830
1831 // Add the comment in green
1832 const commentSpan = document.createElement('span');
1833 commentSpan.style.color = '#6a9955';
1834 commentSpan.textContent = comment;
1835 lineSpan.appendChild(commentSpan);
1836 } else {
1837 processLine(lineSpan, line);
1838 }
1839
1840 temp.appendChild(lineSpan);
1841 temp.appendChild(document.createTextNode('\\n'));
1842 });
1843
1844 function processLine(container, line) {
1845 // Match YAML key-value pattern
1846 const keyMatch = line.match(/^(\\s*)([a-zA-Z_][\\w\\s_-]*?)(:)(.*)$/);
1847 if (keyMatch) {
1848 const [, indent, key, colon, rest] = keyMatch;
1849
1850 // Add indentation
1851 container.appendChild(document.createTextNode(indent));
1852
1853 // Add key in blue
1854 const keySpan = document.createElement('span');
1855 keySpan.style.color = '#9cdcfe';
1856 keySpan.textContent = key;
1857 container.appendChild(keySpan);
1858
1859 // Add colon
1860 container.appendChild(document.createTextNode(colon));
1861
1862 // Process the value
1863 if (rest) {
1864 processValue(container, rest);
1865 }
1866 return;
1867 }
1868
1869 // Match list items
1870 const listMatch = line.match(/^(\\s*)(-)(\\s+)(.*)$/);
1871 if (listMatch) {
1872 const [, indent, dash, space, rest] = listMatch;
1873
1874 // Add indentation
1875 container.appendChild(document.createTextNode(indent));
1876
1877 // Add dash in blue
1878 const dashSpan = document.createElement('span');
1879 dashSpan.style.color = '#569cd6';
1880 dashSpan.textContent = dash;
1881 container.appendChild(dashSpan);
1882
1883 // Add space
1884 container.appendChild(document.createTextNode(space));
1885
1886 // Process the rest
1887 if (rest) {
1888 processValue(container, rest);
1889 }
1890 return;
1891 }
1892
1893 // Default: just add the text
1894 container.appendChild(document.createTextNode(line));
1895 }
1896
1897 function processValue(container, value) {
1898 const trimmed = value.trim();
1899
1900 // Check for quoted strings
1901 if ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
1902 (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
1903 const stringSpan = document.createElement('span');
1904 stringSpan.style.color = '#ce9178';
1905 stringSpan.textContent = value;
1906 container.appendChild(stringSpan);
1907 }
1908 // Check for booleans and null
1909 else if (trimmed === 'true' || trimmed === 'false' || trimmed === 'null') {
1910 const spaces = value.substring(0, value.indexOf(trimmed));
1911 container.appendChild(document.createTextNode(spaces));
1912
1913 const boolSpan = document.createElement('span');
1914 boolSpan.style.color = '#569cd6';
1915 boolSpan.textContent = trimmed;
1916 container.appendChild(boolSpan);
1917 }
1918 // Check for numbers
1919 else if (/^-?\\d+\\.?\\d*$/.test(trimmed)) {
1920 const spaces = value.substring(0, value.indexOf(trimmed));
1921 container.appendChild(document.createTextNode(spaces));
1922
1923 const numSpan = document.createElement('span');
1924 numSpan.style.color = '#b5cea8';
1925 numSpan.textContent = trimmed;
1926 container.appendChild(numSpan);
1927 }
1928 // Default
1929 else {
1930 container.appendChild(document.createTextNode(value));
1931 }
1932 }
1933
1934 return temp.innerHTML;
1935 }
1936 }); // Close DOMContentLoaded
1937 </script>
1938</body>
1939</html>'''
1940
1941 return HTMLResponse(content=html_content)
1942
1943@app.get("/api/config/{path:path}")
1944async def get_config_content(path: str):
1945 """API endpoint to get config file content"""
1946 try:
1947 with open(path, 'r') as f:
1948 content = f.read()
1949 return {"content": content}
1950 except Exception as e:
1951 raise HTTPException(status_code=404, detail=str(e))
1952
1953@app.get("/tests")
1954async def tests_interface():
1955 """Web interface for running and viewing tests"""
1956 html_content = '''<!DOCTYPE html>
1957<html lang="en">
1958<head>
1959 <meta charset="UTF-8">
1960 <meta name="viewport" content="width=device-width, initial-scale=1.0">
1961 <title>DBBasic - Test Runner</title>
1962 <style>
1963 * { margin: 0; padding: 0; box-sizing: border-box; }
1964 body {
1965 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1966 background: #f5f5f5;
1967 height: 100vh;
1968 display: flex;
1969 flex-direction: column;
1970 }
1971 .header {
1972 background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1973 color: white;
1974 padding: 1rem 2rem;
1975 display: flex;
1976 justify-content: space-between;
1977 align-items: center;
1978 }
1979 .logo { font-size: 24px; font-weight: bold; }
1980 .subtitle { font-size: 14px; opacity: 0.9; }
1981 .container {
1982 flex: 1;
1983 padding: 2rem;
1984 overflow-y: auto;
1985 }
1986 .controls {
1987 background: white;
1988 padding: 1rem;
1989 border-radius: 8px;
1990 margin-bottom: 1rem;
1991 display: flex;
1992 gap: 1rem;
1993 align-items: center;
1994 }
1995 .run-btn {
1996 background: #4CAF50;
1997 color: white;
1998 border: none;
1999 padding: 0.75rem 2rem;
2000 border-radius: 6px;
2001 cursor: pointer;
2002 font-weight: 600;
2003 }
2004 .run-btn:disabled {
2005 background: #ccc;
2006 cursor: not-allowed;
2007 }
2008 .results {
2009 background: white;
2010 border-radius: 8px;
2011 padding: 1.5rem;
2012 margin-bottom: 1rem;
2013 }
2014 .test-case {
2015 padding: 0.75rem;
2016 margin: 0.5rem 0;
2017 border-radius: 4px;
2018 border-left: 4px solid #ddd;
2019 font-family: monospace;
2020 font-size: 13px;
2021 }
2022 .test-passed {
2023 border-left-color: #4CAF50;
2024 background: rgba(76, 175, 80, 0.1);
2025 }
2026 .test-failed {
2027 border-left-color: #f44336;
2028 background: rgba(244, 67, 54, 0.1);
2029 }
2030 .test-output {
2031 background: #1e1e1e;
2032 color: #d4d4d4;
2033 padding: 1rem;
2034 border-radius: 4px;
2035 font-family: monospace;
2036 font-size: 13px;
2037 white-space: pre-wrap;
2038 max-height: 400px;
2039 overflow-y: auto;
2040 }
2041 .status-badge {
2042 display: inline-block;
2043 padding: 0.25rem 0.75rem;
2044 border-radius: 15px;
2045 font-size: 12px;
2046 font-weight: 600;
2047 }
2048 .status-success {
2049 background: #d4edda;
2050 color: #155724;
2051 }
2052 .status-error {
2053 background: #f8d7da;
2054 color: #721c24;
2055 }
2056 .spinner {
2057 border: 3px solid #f3f3f3;
2058 border-top: 3px solid #667eea;
2059 border-radius: 50%;
2060 width: 20px;
2061 height: 20px;
2062 animation: spin 1s linear infinite;
2063 display: inline-block;
2064 margin-right: 0.5rem;
2065 }
2066 @keyframes spin {
2067 0% { transform: rotate(0deg); }
2068 100% { transform: rotate(360deg); }
2069 }
2070 </style>
2071</head>
2072<body>
2073 <div class="header">
2074 <div>
2075 <div class="logo">DBBasic</div>
2076 <div class="subtitle">AI Service Test Runner</div>
2077 </div>
2078 <div>
2079 <span>✅ Config → Code → Tests</span>
2080 </div>
2081 </div>
2082
2083 <div class="container">
2084 <div class="controls">
2085 <button class="run-btn" id="runBtn" onclick="runTests()">🧪 Run All Tests</button>
2086 <span id="status">Ready to run tests</span>
2087 </div>
2088
2089 <div class="results" id="results" style="display: none;">
2090 <h3>Test Results</h3>
2091 <div id="testOutput"></div>
2092 </div>
2093 </div>
2094
2095 <script>
2096 async function runTests() {
2097 const runBtn = document.getElementById('runBtn');
2098 const status = document.getElementById('status');
2099 const results = document.getElementById('results');
2100 const testOutput = document.getElementById('testOutput');
2101
2102 // Disable button and show spinner
2103 runBtn.disabled = true;
2104 status.innerHTML = '<span class="spinner"></span>Running tests...';
2105
2106 try {
2107 const response = await fetch('/api/tests/run');
2108 const data = await response.json();
2109
2110 // Show results
2111 results.style.display = 'block';
2112
2113 if (data.success) {
2114 status.innerHTML = '<span class="status-badge status-success">Tests Passed</span>';
2115
2116 let output = '<h4>Test Cases:</h4>';
2117 if (data.test_cases && data.test_cases.length > 0) {
2118 data.test_cases.forEach(test => {
2119 const cssClass = test.status === 'PASSED' ? 'test-passed' : 'test-failed';
2120 output += `<div class="test-case ${cssClass}">
2121 ${test.file}::${test.name} - ${test.status}
2122 </div>`;
2123 });
2124 }
2125
2126 if (data.stdout) {
2127 output += '<h4>Output:</h4><div class="test-output">' + data.stdout + '</div>';
2128 }
2129
2130 testOutput.innerHTML = output;
2131 } else {
2132 status.innerHTML = '<span class="status-badge status-error">Tests Failed</span>';
2133
2134 let output = '<h4>Error:</h4>';
2135 if (data.error) {
2136 output += '<div class="test-output">' + data.error + '</div>';
2137 }
2138 if (data.stderr) {
2139 output += '<h4>Error Output:</h4><div class="test-output">' + data.stderr + '</div>';
2140 }
2141 if (data.stdout) {
2142 output += '<h4>Standard Output:</h4><div class="test-output">' + data.stdout + '</div>';
2143 }
2144
2145 testOutput.innerHTML = output;
2146 }
2147 } catch (error) {
2148 status.innerHTML = '<span class="status-badge status-error">Connection Error</span>';
2149 results.style.display = 'block';
2150 testOutput.innerHTML = '<div class="test-output">Error running tests: ' + error.message + '</div>';
2151 } finally {
2152 runBtn.disabled = false;
2153 }
2154 }
2155 </script>
2156</body>
2157</html>'''
2158
2159 return HTMLResponse(content=html_content)
2160
2161def main():
2162 """Run the AI Service Builder"""
2163 print("\n" + "=" * 60)
2164 print(" DBBasic AI Service Builder")
2165 print(" Create web services from natural language")
2166 print("=" * 60)
2167 print("\nStarting server...")
2168 print("Open http://localhost:8003 in your browser")
2169 print("\nExample services you can create:")
2170 print(" - Calculate shipping costs")
2171 print(" - Validate email addresses")
2172 print(" - Send notifications")
2173 print(" - Classify customer segments")
2174 print(" - Calculate discounts")
2175 print("\nPress Ctrl+C to stop\n")
2176
2177 uvicorn.run(app, host="0.0.0.0", port=8003)
2178
2179if __name__ == "__main__":
2180 main()