How to Ask AI to Write Code That Actually Runs
Short answer: give the AI your language and version, the exact inputs and outputs (with examples), the constraints (libraries, performance, style), and what "done" looks like. Most broken AI code comes from missing context, not from a weak model.
Why AI code breaks
The AI fills gaps with assumptions: a different library version, column names it made up, an input format you don't use. Each assumption is a possible bug.
The coding prompt checklist
- Environment: language, version, framework, OS.
- Inputs and outputs: real examples, including edge cases.
- Existing code or schema: paste the relevant pieces.
- Constraints: allowed libraries, performance needs, style rules.
- Safety: "dry-run by default," "don't delete anything," "no network calls."
- Deliverable: code + how to run it + a test.
Before and after
Before:
write sql to get top customers
After:
Role: You are a senior data analyst. Task: Write a PostgreSQL query for the top 10 customers by revenue in the last 90 days. Schema: customers(id, name); orders(id, customer_id, total_cents, status, created_at). Only count status = 'paid'. Format: Query in one code block, a 3-bullet explanation, and one sanity-check query. Constraints: Convert cents to dollars. Explicit JOINs. Break ties by name.
Why it works: with the schema included, the AI has no column names to invent. Defining "revenue" removes the ambiguity that usually produces a query that runs but returns the wrong answer.
Use examples to pin down behavior
For parsing, regex, and data transformations, list a few inputs that should match and a few that shouldn't. Examples define the problem more precisely than any description.
Debugging prompts
Language/framework: [Node 22, Express]. What I was doing: [action]. What I already tried: [list]. Explain the error in plain English, point to the likely line, give the fix, and tell me how to avoid it. If you need another file, ask instead of guessing. Error:
[paste]
Ask for review, not just code
After the first draft: "Review your own code for edge cases, security issues, and anything that would fail on [10x the data]. List the issues, then fix them."
FAQ
Which AI is best for coding? Several current models are strong. Detailed context improves results from any of them more than switching models does. Should I paste my whole codebase? No. Paste the relevant files, the error, and the interfaces your code touches. Is AI code safe to run? Read it first. For anything that touches files, data, or money, ask for a dry-run mode.