File size: 8,293 Bytes
cf4c7fd |
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 |
"""
spec_validator_v2.py
Strict JSON schema validator + generator for Django backend specs.
"""
import json
import re
from copy import deepcopy
from typing import Dict, Any, List, Tuple
from jsonschema import Draft202012Validator, ValidationError
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import JsonOutputParser
# =====================================================
# FILE LOADERS
# =====================================================
def load_schema(path: str) -> Dict[str, Any]:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def load_json(path: str) -> Dict[str, Any]:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
# =====================================================
# VALIDATION HELPERS
# =====================================================
def _format_error(err: ValidationError) -> Dict[str, str]:
path = "/" + "/".join(map(str, err.absolute_path)) if err.absolute_path else "/"
return {"path": path, "message": err.message}
def validate_schema(
spec: Dict[str, Any],
schema: Dict[str, Any]
) -> List[Dict[str, str]]:
validator = Draft202012Validator(schema)
errors = sorted(validator.iter_errors(spec), key=lambda e: e.path)
return [_format_error(e) for e in errors]
# =====================================================
# SAFE NORMALIZATIONS (SCHEMA-COMPATIBLE ONLY)
# =====================================================
def _to_pascal_case(name: str) -> str:
return "".join(part.capitalize() for part in re.split(r"[_\\s-]+", name) if part)
def normalize_spec(spec: Dict[str, Any]) -> List[str]:
"""
Normalize names without introducing new keys.
"""
warnings = []
# Normalize project name
if "project_name" in spec:
normalized = re.sub(r"[^a-z0-9_]", "_", spec["project_name"].lower())
if normalized != spec["project_name"]:
warnings.append("Normalized project_name")
spec["project_name"] = normalized
# Normalize model names
models = spec.get("apps", {}).get("core", {}).get("models", {})
new_models = {}
for model_name, model_def in models.items():
new_name = _to_pascal_case(model_name)
if new_name != model_name:
warnings.append(f"Renamed model '{model_name}' → '{new_name}'")
new_models[new_name] = model_def
if new_models:
spec["apps"]["core"]["models"] = new_models
return warnings
# =====================================================
# MAIN VALIDATION FUNCTION
# =====================================================
def validate_and_clean_spec(
spec: Dict[str, Any],
schema: Dict[str, Any],
auto_fix: bool = True
) -> Tuple[bool, Dict[str, Any], List[Dict[str, str]], List[str]]:
cleaned = deepcopy(spec)
warnings: List[str] = []
if auto_fix:
warnings.extend(normalize_spec(cleaned))
errors = validate_schema(cleaned, schema)
if errors:
return False, cleaned, errors, warnings
return True, cleaned, [], warnings
# =====================================================
# JSON SPEC GENERATION (LLM)
# =====================================================
def generate_valid_json_spec(
*,
user_prompt: str,
llm,
retries: int = 3,
) -> Dict[str, Any]:
"""
Generates schema-valid JSON using LLM + strict validation.
"""
system_prompt = """
You are a JSON compiler.
Return ONLY a JSON object that EXACTLY matches this schema.
Do NOT add, remove, or rename keys.
Do NOT include explanations or formatting.
Schema:
{{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Minimal Django Backend Generator Spec",
"type": "object",
"required": [
"project_name",
"database",
"auth",
"apps",
"api_config"
],
"properties": {{
"project_name": {{
"type": "string"
}},
"database": {{
"type": "object",
"required": ["engine", "name"],
"properties": {{
"engine": {{
"type": "string",
"enum": ["sqlite", "postgresql"]
}},
"name": {{
"type": "string"
}}
}}
}},
"auth": {{
"type": "object",
"required": ["type"],
"properties": {{
"type": {{
"type": "string",
"enum": ["jwt", "session"]
}}
}}
}},
"apps": {{
"type": "object",
"required": ["core"],
"properties": {{
"core": {{
"type": "object",
"required": ["models", "apis"],
"properties": {{
"models": {{
"type": "object",
"patternProperties": {{
"^[A-Z][a-zA-Z0-9]*$": {{
"type": "object",
"required": ["fields"],
"properties": {{
"fields": {{
"type": "object",
"patternProperties": {{
"^[a-z_][a-z0-9_]*$": {{
"type": "object",
"required": ["type"],
"properties": {{
"type": {{
"type": "string",
"enum": [
"CharField",
"TextField",
"EmailField",
"IntegerField",
"BooleanField",
"DateField",
"DateTimeField",
"ForeignKey"
]
}},
"to": {{
"type": "string"
}}
}}
}}
}}
}}
}}
}}
}}
}},
"apis": {{
"type": "object",
"patternProperties": {{
"^[A-Z][a-zA-Z0-9]*$": {{
"type": "array",
"items": {{
"type": "string",
"enum": ["list", "create", "retrieve", "update", "delete"]
}}
}}
}}
}}
}}
}}
}}
}},
"api_config": {{
"type": "object",
"required": ["base_url"],
"properties": {{
"base_url": {{
"type": "string"
}}
}}
}}
}}
}}
"""
prompt = ChatPromptTemplate.from_messages([
("system", system_prompt),
("user", "{user_prompt}")
])
# usage
schema = load_schema('spec_schema.json')
chain = prompt | llm | JsonOutputParser()
for attempt in range(1, retries + 1):
try:
result = chain.invoke({"user_prompt": user_prompt})
valid, cleaned, errors, _ = validate_and_clean_spec(
result,
schema,
auto_fix=False
)
if valid:
return cleaned
raise ValueError(errors)
except Exception as e:
if attempt == retries:
raise RuntimeError(f"Failed after {retries} attempts: {e}")
raise RuntimeError("Unreachable")
# =====================================================
# CLI (OPTIONAL)
# =====================================================
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Validate Django backend JSON spec")
parser.add_argument("spec", help="Path to spec.json")
parser.add_argument("schema", help="Path to schema.json")
args = parser.parse_args()
schema = load_schema(args.schema)
spec = load_json(args.spec)
valid, cleaned, errors, warnings = validate_and_clean_spec(spec, schema)
print("VALID:", valid)
if warnings:
print("WARNINGS:")
for w in warnings:
print("-", w)
if errors:
print("ERRORS:")
for e in errors:
print(f"{e['path']}: {e['message']}")
else:
print("Spec is valid.")
|