How to Build an AI Code Generation System
Generate code from natural language descriptions using AI.
Jay Banlasan
The AI Systems Guy
An AI code generation system turns plain English descriptions into working code. I use this for scaffolding new modules, writing boilerplate, and generating utility functions across client projects. Instead of writing the same CRUD endpoints for the tenth time, I describe what I need and let AI write the first draft.
The key is building a structured system around it, not just pasting prompts into a chat window.
What You Need Before Starting
- Python 3.8+
- Anthropic API key
- A template library for common patterns
- A code validation step (linting or syntax checking)
Step 1: Define Your Code Templates
TEMPLATES = {
"fastapi_endpoint": {
"system_prompt": """You are a Python developer. Generate FastAPI endpoint code.
Follow these rules:
- Use type hints on all parameters
- Include docstrings
- Return Pydantic models
- Handle errors with HTTPException
- No comments explaining obvious code""",
"language": "python"
},
"sql_query": {
"system_prompt": """You are a SQL expert. Generate SQLite queries.
Follow these rules:
- Use parameterized queries (? placeholders)
- Include CREATE TABLE if schema is needed
- Optimize for read performance
- No ORM, raw SQL only""",
"language": "sql"
},
"bash_script": {
"system_prompt": """You are a DevOps engineer. Generate bash scripts.
Follow these rules:
- Start with #!/bin/bash and set -e
- Use descriptive variable names
- Include error handling
- Log to stdout with timestamps""",
"language": "bash"
}
}
Step 2: Build the Generation Function
import anthropic
from dotenv import load_dotenv
load_dotenv()
def generate_code(description, template_key, model="claude-sonnet-4-20250514"):
template = TEMPLATES.get(template_key)
if not template:
raise ValueError(f"Unknown template: {template_key}")
client = anthropic.Anthropic()
response = client.messages.create(
model=model,
max_tokens=2048,
system=template["system_prompt"],
messages=[{
"role": "user",
"content": f"Generate {template['language']} code for: {description}\n\nReturn ONLY the code, no explanations."
}]
)
code = response.content[0].text
code = code.strip()
if code.startswith("```"):
lines = code.split("\n")
code = "\n".join(lines[1:-1])
return code
Step 3: Add Syntax Validation
import ast
import subprocess
def validate_code(code, language):
if language == "python":
try:
ast.parse(code)
return {"valid": True}
except SyntaxError as e:
return {"valid": False, "error": str(e)}
elif language == "bash":
result = subprocess.run(
["bash", "-n", "-c", code],
capture_output=True, text=True
)
return {"valid": result.returncode == 0, "error": result.stderr}
return {"valid": True, "note": "no validator for this language"}
Step 4: Build the CLI Interface
import argparse
import os
def main():
parser = argparse.ArgumentParser(description="Generate code with AI")
parser.add_argument("description", help="What the code should do")
parser.add_argument("--template", "-t", default="fastapi_endpoint", choices=TEMPLATES.keys())
parser.add_argument("--output", "-o", help="Output file path")
args = parser.parse_args()
print(f"Generating {args.template} code...")
code = generate_code(args.description, args.template)
template = TEMPLATES[args.template]
validation = validate_code(code, template["language"])
if not validation["valid"]:
print(f"Warning: generated code has issues: {validation.get('error')}")
if args.output:
with open(args.output, "w") as f:
f.write(code)
print(f"Saved to {args.output}")
else:
print(code)
if __name__ == "__main__":
main()
Step 5: Use It
python codegen.py "CRUD endpoints for a user model with name, email, and role fields" -t fastapi_endpoint -o routes/users.py
python codegen.py "Query to find all users who signed up in the last 30 days grouped by role" -t sql_query
What to Build Next
Add a feedback loop. When you edit the generated code, log what you changed. Over time, feed those corrections back into the system prompts so the output gets closer to your style.
Related Reading
- Claude Code: The AI Coding Tool That Changes Operations - how AI coding tools fit into real workflows
- Building Your First Automation: A Complete Guide - starting with automation fundamentals
- The Testing Pyramid for AI Operations - testing generated code properly
Want this system built for your business?
Get a free assessment. We will map every system your business needs and show you the ROI.
Get Your Free Assessment