File size: 3,735 Bytes
cce8120 | 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 | import os
from typing import Dict, Any, Optional, List
from backend.builder.engine import AutonomousCodeBuilder
class AIBuilderService:
def __init__(self, workspace_root: str = "."):
self.builder = AutonomousCodeBuilder(workspace_root=workspace_root)
def generate_project(self, prompt: str, template: str = "fastapi-react") -> Dict[str, Any]:
"""Generates a complete multi-file project scaffold from a prompt."""
result = self.builder.generate_project(prompt, template=template)
return {
"status": "success",
"prompt": prompt,
"template": template,
"generated_files": result.get("files", []) if isinstance(result, dict) else []
}
def generate_component(self, name: str, description: str, framework: str = "react") -> Dict[str, Any]:
"""Generates an isolated UI component or module."""
filename = f"components/{name.lower()}.tsx" if framework == "react" else f"components/{name.lower()}.py"
code_content = f"""// Generated {framework.capitalize()} Component: {name}
// Description: {description}
export default function {name}() {{
return (
<div className="p-4 border rounded-lg shadow-sm">
<h2 className="text-xl font-bold">{name}</h2>
<p className="text-gray-600">{description}</p>
</div>
);
}}
"""
return {
"status": "success",
"component_name": name,
"framework": framework,
"filepath": filename,
"code": code_content
}
def generate_api(self, endpoint_path: str, method: str, description: str) -> Dict[str, Any]:
"""Generates a FastAPI router endpoint from specifications."""
func_name = endpoint_path.strip("/").replace("/", "_").replace("-", "_") or "root"
code_content = f"""# Generated FastAPI Endpoint
# Description: {description}
@app.{method.lower()}("{endpoint_path}")
async def {func_name}():
\"\"\"{description}\"\"\"
return {{"status": "ok", "endpoint": "{endpoint_path}"}}
"""
return {
"status": "success",
"endpoint": endpoint_path,
"method": method.upper(),
"code": code_content
}
def generate_schema(self, table_name: str, fields: List[Dict[str, str]]) -> Dict[str, Any]:
"""Generates Pydantic & SQLAlchemy data schemas from field specs."""
class_name = "".join(word.capitalize() for word in table_name.split("_"))
pydantic_fields = []
for field in fields:
fname = field.get("name", "id")
ftype = field.get("type", "str")
pydantic_fields.append(f" {fname}: {ftype}")
pydantic_code = f"class {class_name}Base(BaseModel):\n" + "\n".join(pydantic_fields)
return {
"status": "success",
"table_name": table_name,
"pydantic_model": pydantic_code
}
def generate_pipeline(self, target: str = "docker") -> Dict[str, Any]:
"""Generates deployment scripts, Dockerfiles, or systemd services."""
if target == "docker":
content = """FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "8000"]
"""
filename = "Dockerfile"
else:
content = """#!/usr/bin/env bash
echo "Building package..."
"""
filename = "deploy.sh"
return {
"status": "success",
"target": target,
"filename": filename,
"content": content
}
builder_service = AIBuilderService()
|