I Struggled to Get AI to Write Useful Code — Here's What Finally Worked A developer struggling with unreliable AI-generated code for a microservice project built a Python prompt generator that produces detailed, structured prompts with examples, resulting in consistent, copy-pasteable Flask routes with SQLAlchemy and Marshmallow. The technique treats the AI like a diligent intern requiring explicit instructions, including system messages defining the tech stack and low-temperature settings for deterministic output. After implementing this approach, the developer was able to directly copy AI-generated endpoint code with minimal tweaks, saving hours of boilerplate work. Last month, I had to build a dozen API endpoints for a new microservice. I knew the patterns – CRUD operations, SQLAlchemy models, Pydantic schemas – but typing out all that boilerplate felt soul-crushing. I turned to AI, hoping it would save me hours. What followed was a rollercoaster of bad outputs, hallucinations, and frustration. But after a week of failed attempts, I found a prompting approach that actually produced reliable, copy-pasteable code. This isn't a “just use this tool” story. It's about the technique that finally worked for me, with real examples you can adapt. I started with the obvious: “Write a Flask route for creating a user.” The AI spat back something like: python @app.route '/users', methods= 'POST' def create user : data = request.json Create user logic return jsonify {'id': 1, 'username': 'john'} Hardcoded response Not even using the input. I tried again: “Write a proper endpoint with validation.” It gave me a mix of Flask and FastAPI syntax. Maddening. I realized the problem was me. I was asking AI to read my mind. It didn't know my database schema, error handling patterns, or even which ORM I used. I tried several things that made things worse: I stopped treating the AI like a senior developer and started treating it like a diligent intern who needs extremely detailed instructions. The key was to provide: Here's the actual approach that clicked for me. I built a prompt generator in Python. It takes a schema description and produces a prompt with examples: php import requests def generate endpoint code schema json: dict - str: system msg = "You are a Python backend developer. You write Flask routes with SQLAlchemy and Marshmallow. Always include error handling and docstrings." examples = { "input": '{"model": "Project", "fields": "id", "name", "created at" }', "output": ''' routes/projects.py from flask import Blueprint, request, jsonify from models import db, Project from schemas import ProjectSchema projects bp = Blueprint 'projects', name @projects bp.route '/projects', methods= 'POST' def create project : schema = ProjectSchema try: data = schema.load request.json except ValidationError as err: return jsonify err.messages , 400 project = Project data db.session.add project db.session.commit return jsonify schema.dump project , 201 ''' } Build the prompt with examples + new request user prompt = f""" Generate a Flask endpoint for creating a resource based on the following schema: {schema json} Use the same style as the examples below. Here is an example: Example input: {examples 0 'input' } Example output: {examples 0 'output' } Now generate for this input: {schema json} """ response = requests.post "https://api.openai.com/v1/chat/completions", headers={"Authorization": "Bearer YOUR KEY"}, json={ "model": "gpt-4", "messages": {"role": "system", "content": system msg}, {"role": "user", "content": user prompt} , "temperature": 0.2 low creativity for deterministic output } return response.json 'choices' 0 'message' 'content' After this change, the AI started generating code that: request.json I could then copy the output directly into my project, only tweaking a few details. This approach isn't magic. Here's what I wish someone had told me: from sqlalchemy import Column, Integer, String that was fine, but it once invented a from flask sqlalchemy import db that doesn't exist without extension setup. datamodel-code-generator for Pydantic models and only use AI for the wiring routes, error handling .AI code generation can save you from burnout on boilerplate, but it's not a silver bullet. The trick is to give the model the right amount of structure – not too vague, not too rigid. Embrace few-shot prompting. And always, always review the output. I'm still early in this journey. How do you handle AI-generated code in your workflow? Do you rely on prompts, or have you built a custom tool around it? I'd love to hear what works for you.