Coding Prompts That Work: A Workflow from Context to Verified Code
A practical workflow for AI-assisted coding: give the right context, set constraints, generate in small steps, verify with tests, review and security checks, and iterate. Links to individual coding templates for each step.
Most bad AI-generated code comes from one of two gaps: the model didn't have the context it needed, or nobody checked the result properly. Better wording helps less than closing those two gaps.
This guide is a workflow, not another list of prompts. It follows five stages:
- Context: what the model needs to know
- Constraints: what the answer must and must not do
- Generation: asking for small, reviewable pieces
- Verification: tests, review and security checks
- Iteration: feeding back precise failures and keeping what works
If you want copy-paste prompts for specific tasks, use the companion 50 ChatGPT prompts for developers or the individual templates linked throughout this guide.
Stage 1: Context
A model can't see your repository, your runtime, your team's conventions or the bug report unless you give them to it (or use a tool that loads them). Weak prompts usually aren't too short; they're missing facts.
Weak:
Fix this bug
[code]
Strong:
Goal: this FastAPI endpoint should return unique user IDs, sorted ascending.
Actual: the response contains duplicates. No error is raised.
Reproduce: GET /users/active with two sessions for the same user.
Environment: Python 3.12, FastAPI, SQLAlchemy 2.x, PostgreSQL.
Relevant code:
[the endpoint and the query function it calls]
Related types:
[the Session and User models]
A context checklist
Include what applies:
- Goal and intent: what the code should do, in one or two sentences
- Actual behavior: error messages, stack traces, wrong output, with the exact text
- Reproduction: the input, request or steps that trigger the problem
- Environment: language and framework versions, key libraries, runtime
- Relevant code: the function plus what it calls and what calls it, not the whole file
- Interfaces: types, schemas, API contracts the code must respect
- Existing patterns: a short example of how your codebase already does similar things
- What you've tried: so the model doesn't suggest it again
How much code to include
Paste the code the change depends on: the function, its direct callers, the types it uses, and any middleware or configuration that affects it. A focused 50-150 lines with a sentence about where it sits usually beats a 2,000-line paste, because the model has less irrelevant code to misread. If you use an AI coding tool that can read your repository, put stable context in its project instruction files instead (see "Make context reusable" below).
Stage 2: Constraints
Context tells the model about the world. Constraints tell it what a correct answer looks like. Without them, models tend to rewrite more than you asked, add dependencies, or pick a different style.
Useful constraints:
- Scope: "Change only
get_active_users. Do not modify the route signature." - Dependencies: "Use only libraries already in requirements.txt."
- Compatibility: "Keep the public API unchanged; existing callers must keep working."
- Performance: "The table has ~5 million rows; avoid loading all rows into memory."
- Security: "Inputs come from unauthenticated users. Validate and bound them."
- Style: "Follow the existing error-handling pattern shown above."
- Output format: "Return a unified diff" or "Return the full function, then the test."
A compact template that combines Stages 1 and 2:
## Goal
[WHAT THE CODE SHOULD DO]
## Current behavior
[ERROR / WRONG OUTPUT / "new feature"]
## Environment
[LANGUAGE, FRAMEWORK, KEY LIBRARIES AND VERSIONS]
## Relevant code
[CODE THE CHANGE DEPENDS ON]
## Constraints
- Change only: [SCOPE]
- Must keep: [PUBLIC API / BEHAVIOR]
- Allowed dependencies: [LIST OR "existing only"]
- Performance/security requirements: [REQUIREMENTS]
## Output
[DIFF / FULL FUNCTION / PLAN FIRST], plus tests in [FRAMEWORK]
Stage 3: Generation
Ask for a plan before code on anything non-trivial
Before writing code, list the changes you would make (files, functions,
and why), any assumptions you're making, and any questions where the
answer would change the approach. Wait for my reply.
Reading a five-line plan is faster than reviewing 200 lines of code built on a wrong assumption.
Generate in small, testable steps
Break larger features into steps you can run between prompts. For example, building a rate limiter:
- "Explain the sliding-window approach for our case and the data structure you'd use in Redis. No code yet."
- "Implement it as a single function with type hints. Use only
redis-py, which we already depend on." - "Write tests for it using our existing test setup: allowed requests, blocked requests, and window rollover."
- "Add handling for Redis connection failures. Decide with me first: should requests fail open or closed?"
Each step produces something you can verify before continuing. Step 4 also shows a pattern worth copying: when a decision is a product or risk choice, make the model ask instead of decide.
Ask for tests with the code
Requesting tests in the same response gives you a way to check the code immediately, and writing the tests often surfaces cases the model would otherwise ignore. Better still, for bug fixes, ask for a test that fails before the fix and passes after it.
Templates for this stage: API Endpoint Designer, React Component Generator with TypeScript, Database Migration Script Writer, and Unit Test Generator.
Stage 4: Verification
Treat AI-generated code as a pull request from a fast contributor who doesn't know your system: often useful, sometimes subtly wrong, never merged unread.
Verification checklist
Tests
- The code runs, and the existing test suite passes
- New tests cover the changed behavior, including at least one failure or edge case
- For bug fixes, a regression test fails before the fix and passes after
- Tests actually assert outcomes (not just "doesn't throw")
- You ran the tests yourself; you didn't take the model's word that they pass
Review
- You read the whole diff, including parts you didn't ask to change
- The change matches the intent and stays within the requested scope
- Every API, function or flag it uses actually exists in your versions (check the docs; models can invent plausible-looking APIs)
- Error handling matches your codebase's pattern
- No new dependency was added without a reason you agree with
Security
- Untrusted input is validated and bounded (size, type, range)
- Database queries are parameterized; no string-built SQL or shell commands
- New data access is authorized and scoped to the caller
- No secrets, tokens or credentials in code, logs or error messages
- New dependencies are real, maintained packages with the name you expect
For a structured way to run AI-assisted reviews, including a triage rubric for false positives, see the AI code review workflow guide. Templates: Code Review Assistant for Pull Requests and the code review skill.
A verification prompt you can reuse
After generating code, a second, separate prompt that only reviews it can catch problems the generating prompt missed:
Review the code below, which was written to meet these requirements:
[REQUIREMENTS AND CONSTRAINTS FROM STAGE 2]
[GENERATED CODE]
List: (1) requirements it doesn't meet, (2) inputs that would break it,
(3) security issues, (4) any function or API call you're not certain
exists in [LIBRARY VERSION]. For each, give the line and the evidence.
If you find nothing, say so.
This doesn't replace running the tests. It is a cheap extra filter.
Stage 5: Iteration
Feed back precise failures
"It doesn't work" gives the model nothing to go on. Paste the evidence:
The test test_window_rollover fails:
[EXACT TEST OUTPUT / STACK TRACE]
Keep the existing passing tests unchanged. Fix only what's needed for
this test to pass, and explain the cause in one or two sentences.
Know when to start over
Long back-and-forth threads accumulate wrong assumptions. If the model keeps reintroducing the same mistake, start a new conversation with an updated context packet that states the correction up front ("Note: the orders table has no deleted_at column").
Keep what works
When a prompt reliably produces good results, save it as a template with placeholders. When you find yourself repeating the same context (stack, conventions, "don't use library X"), move it into a reusable place, as described next.
Make Context Reusable
AI coding tools can load project-level instructions automatically, so you don't have to repeat your stack and conventions in every prompt (all checked 2026-11-05):
- Cursor reads project rules from
.cursor/rulesas.mdcfiles and also supportsAGENTS.md(Cursor docs). - Claude Code reads
CLAUDE.mdfiles for persistent project instructions and can also useAGENTS.md(Claude Code docs). - GitHub Copilot reads
.github/copilot-instructions.md, path-specific instruction files, andAGENTS.md(GitHub docs).
Good candidates for these files: the stack and versions, how to run tests, error-handling and logging conventions, directories not to touch, and known pitfalls. Keep them short and specific. See how to write Cursor rules, and browse ready-made examples for Cursor, Claude Code and GitHub Copilot.
For repeatable multi-step tasks, a reusable skill can package instructions and reference material together. Starting points: code review, debug helper, refactor and test generator.
Templates by Workflow Step
| Task | Template |
|---|---|
| Diagnose a bug | Debug Helper |
| Review a pull request | Code Review Assistant for Pull Requests |
| Refactor safely | Refactoring Assistant |
| Write unit tests | Unit Test Generator, Jest Unit Test Generator |
| Document code | Documentation Generator |
| Write or tune SQL | SQL Query Optimizer and Explainer |
| Design an endpoint | API Endpoint Designer |
| Write a migration | Database Migration Script Writer |
| Commit message | Git Commit Message Generator |
Browse everything in coding prompts, or by use case: debugging, code review and documentation.
Common Mistakes
| Mistake | Fix |
|---|---|
| No versions ("write a function to parse JSON") | State language, framework and library versions |
| No error text ("my code doesn't work") | Paste the exact error, stack trace or wrong output |
| Pasting the whole file or repo | Paste the function, its callers and its types |
| No constraints ("optimize this") | Say what to optimize for and what can't change |
| Accepting code without running it | Run tests; read the full diff |
| Letting the model make product decisions | Ask it to list decisions and wait for your answer |
Frequently Asked Questions
Should I include my whole codebase in prompts?
No. Include the code the change depends on and a sentence about where it fits. For repository-wide context, use your coding tool's project instruction files.
How do I get AI to follow my team's coding style?
Show a short example of existing code in your style, state the conventions explicitly, and put them in your tool's project instruction file so they apply every time.
Is AI-generated code safe to use in production?
Only after the same review and testing you would apply to any contributor's code. Pay particular attention to input validation, authorization, dependencies and API calls that may not exist in your versions.
Which AI model is best for coding?
Models change frequently, so we don't rank them here. Try candidates on a few real tasks from your codebase, with the same prompts and the verification checklist above, and compare how often the output passes your tests and review.
How do I get better at coding prompts?
Save prompts that work as templates, note which context made the difference, and move repeated context into instruction files. The prompt library is a good place to start from instead of writing every prompt from scratch.
Related Articles
50 ChatGPT Prompts for Developers, With Example Output Shapes
50 copy-paste prompts for debugging, code review, documentation, refactoring and everyday dev tasks, with illustrative input and output examples for the five most useful ones and notes on verifying results.
AI Code Review Workflow: Prompts, Triage Rubric and a Worked Diff Example
A repeatable AI code review workflow: what context to give the model, a review prompt that demands evidence, a triage rubric for false positives, human checks, and how to package it as a reusable review skill.
What Is Prompt Engineering? Definition, Core Techniques and Examples
What prompt engineering is, what it can and cannot fix, the core techniques with examples, and how practitioners test prompts, with links to Anthropic and OpenAI's official guidance.