File size: 5,217 Bytes
71b4454 7fab749 71b4454 7fab749 71b4454 7fab749 71b4454 | 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 | import os
from typing import Dict, Any, List
from backend.builder.engine import AutonomousCodeBuilder
from backend.models.gateway import model_gateway, DEFAULT_MODEL
from backend.tools.knowledge_loader import build_prompt_with_knowledge
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]:
"""
Generate a production project scaffold and write it to disk.
(Kept template-based: multi-file scaffolding is a structural
operation, not a single free-text generation.)
"""
files: Dict[str, str] = {
"README.md": f"""# Generated Project
Prompt:
{prompt}
""",
".gitignore": """__pycache__/
*.pyc
.env
node_modules/
dist/
build/
""",
}
if template == "fastapi-react":
files.update(
{
"backend/main.py": """from fastapi import FastAPI
app = FastAPI(title="Generated API")
@app.get("/")
async def root():
return {"status": "ok"}
""",
"backend/requirements.txt": """fastapi
uvicorn
""",
"frontend/package.json": """{
"name": "generated-app",
"private": true,
"version": "1.0.0"
}
""",
"frontend/src/main.tsx": """export default function App() {
return <h1>Generated Project</h1>;
}
""",
}
)
created_files = self.builder.generate_project(files)
return {
"status": "success",
"prompt": prompt,
"template": template,
"generated_files": created_files,
"file_count": len(created_files),
}
async def generate_component(
self,
name: str,
description: str,
framework: str = "react",
) -> Dict[str, Any]:
"""Generate a real UI component via LLM."""
filename = (
f"components/{name.lower()}.tsx"
if framework == "react"
else f"components/{name.lower()}.py"
)
prompt = (
f"Write a single {framework} component named {name}. "
f"Description: {description}. "
f"Output ONLY the code, no explanation, no markdown fences."
)
result = await model_gateway.generate(DEFAULT_MODEL, prompt)
return {
"status": "success",
"component_name": name,
"framework": framework,
"filepath": filename,
"code": result["text"],
"provider": result["provider"],
"model": result["model"],
}
async def generate_api(
self,
endpoint_path: str,
method: str,
description: str,
) -> Dict[str, Any]:
"""Generate a real FastAPI endpoint via LLM."""
base_prompt = f"Write a production FastAPI route for {method.upper()} {endpoint_path}. Description: {description}. Assume app = FastAPI() exists. Include all imports."
prompt = build_prompt_with_knowledge(base_prompt, f"fastapi {description}")
result = await model_gateway.generate(DEFAULT_MODEL, prompt)
return {
"status": "success",
"endpoint": endpoint_path,
"method": method.upper(),
"code": result["text"],
"provider": result["provider"],
"model": result["model"],
}
async def generate_schema(
self,
table_name: str,
fields: List[Dict[str, str]],
) -> Dict[str, Any]:
"""Generate a real Pydantic model via LLM."""
model_name = "".join(word.capitalize() for word in table_name.split("_"))
field_desc = ", ".join(f"{f['name']}: {f['type']}" for f in fields)
base_prompt = f"Write a production Pydantic BaseModel named {model_name}Base with fields: {field_desc}. Include SQLAlchemy model too."
prompt = build_prompt_with_knowledge(base_prompt, "fastapi pydantic sqlalchemy")
result = await model_gateway.generate(DEFAULT_MODEL, prompt)
return {
"status": "success",
"table_name": table_name,
"pydantic_model": result["text"],
"provider": result["provider"],
"model": result["model"],
}
def generate_pipeline(
self,
target: str = "docker",
) -> Dict[str, Any]:
"""Kept template-based: deployment configs need to be exact/reliable,
not creatively generated."""
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,
}
|