The short answer: Good prompts for AI coding assistants read like good tickets: they state the goal, give the relevant context (files, types, conventions), spell out constraints, define what "done" looks like, and ask for a specific output format. Ask for a plan before code on anything non-trivial, show an example when you want a particular style, work in small iterations rather than one giant request, and put recurring instructions in project instruction files instead of retyping them. Then verify everything with tests and review.
Two developers using the same AI coding tool on the same codebase can get very different results. Usually it isn't luck or talent with "magic words." The difference is that one of them gives the assistant what a capable new colleague would need to do the task well, and the other types half a sentence and hopes.
Prompting for code is less about clever phrasing than about clear communication. Modern assistants are good at following detailed instructions and bad at reading minds. This guide covers the patterns that consistently improve output, the anti-patterns that consistently degrade it, how to build reusable prompts for your team, and how to tell whether a prompt actually works better.
The anatomy of a good coding prompt
A useful mental model: write the prompt you'd want if you were handed this task cold. Most good coding prompts contain five parts.
- Goal: what you want and why, in one or two sentences. The "why" matters, because it lets the assistant make sensible decisions you didn't anticipate.
- Context: the files, types, functions and conventions involved. Point to them by name, or include them.
- Constraints: what must not change, libraries to use or avoid, performance or compatibility requirements.
- Definition of done: the tests that should pass, the behaviour to verify, the edge cases to handle.
- Output format: a diff, a plan, a single function, an explanation first: whatever you need.
Compare these two prompts for the same task:
Weak:
add caching to the product api
Strong:
Add caching to GET /api/products/:id (src/app/api/products/[id]/route.ts).
Product pages are getting slow under load, and product data changes rarely.
Context:
- We already use Redis via src/lib/redis.ts (see getJSON / setJSON helpers).
- Products are updated through src/lib/products/update.ts.
Constraints:
- Cache for 10 minutes.
- Invalidate the cache entry when a product is updated.
- Don't change the response shape.
Done when:
- A cache hit skips the database query (add a test for this).
- Updating a product invalidates its cache entry (add a test).
- Existing tests in src/app/api/products still pass.
Start with a short plan, then implement.
The second takes a minute longer to write and saves several rounds of correction. It names the files, reuses existing helpers instead of inviting a new caching library, covers invalidation (which the weak prompt would probably have missed), and gives the assistant a way to check its own work.
Pattern 1: specification first
For anything beyond a small edit, describe the behaviour precisely before asking for code. Inputs, outputs, error cases and examples are more useful than adjectives. "Handle errors gracefully" means nothing specific; "return 404 with { error: 'NOT_FOUND' } when the product doesn't exist, and 400 when the ID isn't a valid UUID" can be implemented and tested.
Writing the specification often reveals that you hadn't decided something yet. That's a feature: it's much cheaper to decide before the code exists. Pairing this with tests is the idea behind the guide to test-driven development with AI assistants.
Pattern 2: plan before code
On non-trivial tasks, ask for a plan first: which files will change, what the approach is, what the risks are. Review it, correct it, then ask for the implementation. Many tools have a dedicated planning mode for this. A plan takes seconds to read, and catching a wrong approach at that stage saves reviewing (and discarding) hundreds of lines of code.
Plans are also where you spot misunderstandings: the assistant planning to add a new dependency when you have an existing helper, or to modify a shared module that other teams rely on. Redirecting at the plan stage is far cheaper than after implementation.
Pattern 3: show, don't just tell
When you want output in a particular style, an example beats a description. If your project has a conventional way of writing API handlers, point the assistant to an existing one: "Follow the structure of src/app/api/orders/route.ts: validation with zod at the top, the service call, then the response mapping." Assistants are very good at pattern-matching against a concrete example and much less reliable at following abstract style rules.
The same applies to tests, error messages, commit messages and documentation. One good example in the prompt, or a reference to one in the codebase, sets the pattern for everything that follows.
Pattern 4: small iterations
Large, one-shot requests ("build the whole billing module") produce large, hard-to-review output with mistakes buried in it. Break work into steps that each produce something you can check: the data model, then the service function with tests, then the API route, then the UI. Review and commit between steps. If a step goes wrong, you lose one step, not the whole effort.
Iteration also helps the assistant: each step's result becomes context for the next, and it's working from verified code rather than its own earlier guesses.
Pattern 5: ask for reasoning where it matters
For algorithms, tricky bugs and design decisions, ask the assistant to explain its reasoning or compare options before committing to one: "List two or three approaches to deduplicating these events, with trade-offs, and recommend one." This surfaces assumptions you can check and often produces a better choice than the first idea. For routine edits it's unnecessary overhead, so save it for decisions that are hard to reverse.
Prompts for common tasks
Debugging
This test fails intermittently in CI but passes locally:
[test name and file]
Error output:
[paste the actual error and stack trace]
Recent changes: [relevant commits or PR]
First explain the most likely root causes, ranked. Then reproduce it if you can
(run the test in a loop), confirm the cause, and propose a fix with a test that
fails before the fix and passes after. Don't change unrelated code.
Real evidence (error output, logs, reproduction steps) is the single biggest factor in debugging quality. "It's broken" gives the assistant nothing to work with.
Code review
Review this diff for: correctness bugs, missing error handling, security issues
(especially authorisation on new endpoints), and missing tests.
Ignore formatting and style; our linter handles those.
Report only real problems, ranked by severity, each with the file, line and a
suggested fix. If you find nothing significant, say so.
Telling the assistant what to ignore and that "nothing significant" is an acceptable answer cuts down on the filler comments that make AI reviews tiresome.
Refactoring
Refactor src/lib/billing/invoice.ts to separate calculation from formatting.
Behaviour must not change: all tests in src/lib/billing must pass before and after.
Do it in small commits, running the tests after each step.
Don't change any public function signatures.
Writing tests for existing code
Write tests for parseCsvImport in src/lib/import.ts.
Cover: valid files, missing required columns, extra columns, empty files,
quoted fields with commas, and invalid dates. Follow the style of
src/lib/export.test.ts. Expected values must come from the specification
below, not from running the current code: [spec]
The last line matters: tests generated by running the code and recording its output only prove the code does what it already does, bugs included.
Anti-patterns that degrade output
- Vague goals. "Make it better" or "optimise this" invite arbitrary changes. Say what better means.
- Missing context. Asking for code that should use your existing helpers without telling the assistant they exist produces duplicate utilities.
- Kitchen-sink requests. Bundling a feature, a refactor and a dependency upgrade into one prompt produces one tangled change that's hard to review.
- Accepting the first answer. The first output is a draft. Review it, push back, ask "what could break?"
- Fighting the same correction repeatedly. If you correct the same thing in every session, it belongs in a project instruction file, not in your next prompt.
- Endless conversation threads. Long sessions accumulate stale context and earlier mistakes. Start a fresh session for a new task, carrying over only what's needed.
Project instruction files: prompts that apply every time
Most coding assistants read a project-level instruction file automatically (names vary by tool: GitHub Copilot uses repository instruction files, Cursor uses rules files, and Claude Code reads CLAUDE.md). This is the most valuable prompt you'll write, because it's applied to every request. Good ones are short and factual:
# Project notes for AI assistants
## Commands
- Install: pnpm install
- Test: pnpm test (unit), pnpm test:e2e (end to end, slow)
- Lint and types: pnpm lint && pnpm typecheck
## Conventions
- API handlers validate input with zod and return { error: CODE } on failure.
- Use src/lib/db for database access; never import the driver directly.
- Dates are stored in UTC and formatted with src/lib/dates.
## Rules
- Never modify tests to make them pass; explain instead.
- Don't add dependencies without asking.
- Don't touch src/legacy/ or generated files in src/gen/.
Keep it current, review changes to it like code, and resist turning it into an essay. Every line costs attention on every request, so include what genuinely changes the output.
Building a personal or team prompt library
When you find a prompt that works well for a recurring task (reviewing migrations, writing release notes, triaging a bug report), save it. Many tools support reusable commands, snippets or skills, so a good prompt becomes one keystroke. For a team, keep shared prompts in the repository, where they can be reviewed and improved like code, and note what each one is for and when it was last checked.
Checking whether a prompt is actually better
It's easy to convince yourself a new prompt is better from one good result. For prompts you use often, compare them properly: run old and new versions on the same handful of real tasks, and check results against something objective, such as tests passing, review comments needed, or time to a mergeable change. The same evaluation habits that apply to AI features in products apply here, as covered in the guide to testing LLM features with evals.
Giving the right context
Context is the raw material of every good answer, and it's also where most prompts go wrong, in both directions. Too little and the assistant invents helpers, guesses at types and ignores conventions. Too much and the important details get lost among irrelevant files, the request gets slower and more expensive, and the assistant may latch on to the wrong example.
A few habits keep context useful:
- Name the files that matter. Most tools let you reference files or symbols directly. Point to the file being changed, the types it uses, one example of the pattern to follow and the relevant tests. That's usually enough.
- Include real data shapes. A sample API response, a database row or a type definition removes a whole class of guesses about field names and nesting.
- Paste actual errors, not summaries. "It throws a type error" loses the information the assistant needs; the full message and stack trace contain it.
- State what you've already tried. When debugging, listing the approaches that didn't work stops the assistant suggesting them again.
- Leave out the irrelevant. Attaching a whole directory "just in case" dilutes attention. If a file doesn't affect the task, it doesn't belong in the prompt.
Agents that can search the codebase themselves reduce how much you need to supply by hand, but they still benefit from a starting point. "The bug is somewhere in the checkout flow, probably around src/lib/cart" saves the agent exploring the entire repository and lowers the chance it fixes a similar-looking problem in the wrong place.
Prompts for working with legacy code
Legacy code is where AI assistance can help most and where careless prompts do the most damage. Old code often has undocumented behaviour that other parts of the system rely on, and an assistant asked to "clean this up" will happily remove a quirk that something depends on.
A safer sequence for legacy changes:
- Ask for an explanation first. "Explain what this module does, including any surprising behaviour or side effects, and list everything that calls it." Read the answer carefully, and verify the surprising parts yourself.
- Pin down current behaviour with tests. Ask for characterisation tests that record what the code does today, including the odd cases. These tests exist to detect change, not to judge correctness.
- Change in small steps. Refactor with the characterisation tests running after each step, so any change in behaviour shows up immediately.
- Change behaviour deliberately. When you do want different behaviour, update the relevant test first, in its own commit, so reviewers can see exactly what changed and why.
This turns a risky "rewrite this old module" request into a controlled process, and it produces a test suite the module probably never had.
Prompting for performance and security work
General-purpose prompts tend to produce general-purpose code: correct in the common case, unremarkable in performance and only as secure as the patterns the assistant happens to follow. When performance or security matters, say so explicitly and give the assistant something concrete to work against.
For performance, describe the actual problem with numbers: "This endpoint takes 2 seconds for accounts with 10,000 orders; the query plan is below. Find the bottleneck and propose changes, with expected impact." Ask it to explain the cause before changing anything, and measure before and after. Optimisation without measurement tends to make code more complex without making it faster.
For security, name the threats you care about: "This endpoint is called by authenticated users of many tenants. Check that a user can only access their own tenant's data, that input is validated, and that nothing sensitive is logged." A prompt that lists specific risks gets far more useful answers than "make it secure," and it doubles as a review checklist for the human who checks the result.
Prompting agents versus chat assistants
The same habits apply to chat assistants and to agents that act on their own, but agents raise the stakes, because they take many steps between your prompt and the result. A vague chat prompt produces one disappointing answer you can correct; a vague agent prompt can produce twenty file changes heading in the wrong direction.
When prompting an agent, add a few things a chat prompt doesn't need:
- Boundaries. Which directories it may change, which it must not touch, and whether it may add dependencies or change configuration.
- Checkpoints. "Show me the plan before editing" or "stop after the data layer so I can review" keeps long tasks on track.
- A verification step. Tell it which commands prove the work is done: the test command, the type checker, the linter. Agents that verify their own work produce far better results.
- What to do when stuck. "If a test fails for a reason unrelated to this task, stop and tell me" prevents an agent from wandering into unrelated fixes.
- The shape of the final report. Ask for a summary of what changed, what was tested and anything uncertain. It makes review much faster.
Agents also benefit from narrower tasks than you might give a person. "Migrate the user settings page to the new form library" is a good agent task; "modernise the frontend" is not. Breaking large goals into agent-sized tasks is a skill in itself, and it's the same skill as writing good tickets for a team.
A prompt review checklist
Before sending a prompt for any task that matters, a ten-second check catches most problems:
- ☐ Is the goal clear, including why?
- ☐ Have I named the relevant files, types and an example to follow?
- ☐ Have I said what must not change?
- ☐ Is there a checkable definition of done, ideally tests?
- ☐ Is the task small enough to review in one sitting?
- ☐ For larger tasks, am I asking for a plan first?
- ☐ Is anything here something I keep repeating that belongs in the project instructions?
It sounds bureaucratic, but it quickly becomes habit, and it's the cheapest quality improvement available. Most disappointing AI output traces back to one of these boxes being unchecked.
Same prompt, different models
A prompt that works beautifully with one model can behave differently with another, and most tools now let you switch models. Larger models tend to handle vague instructions and long, complex tasks better; smaller, faster models do well on narrow, clearly specified tasks but need more explicit instructions. If you switch models for cost or speed, re-run a few of your saved prompts on real tasks and check the output before relying on it. Clear, specific prompts transfer between models far better than prompts that lean on one model's quirks, which is another reason to favour plain, explicit instructions over clever phrasing.
Practising the habit
Prompting improves with deliberate practice. For a week, before sending any prompt for a real task, spend thirty seconds adding the missing parts from the anatomy above: the why, the files, the constraints, the definition of done. Then compare the results with your usual quick prompts. Most developers find the difference obvious within a few days, and the habit sticks because the payoff is immediate: fewer rounds of correction and less code to throw away.
Share what you learn with your team as well. A good prompt that one developer discovers becomes far more valuable once it's saved in the repository, refined by others and applied consistently. Over a few months, a shared library of prompts and a well-maintained project instruction file can lift the whole team's results more than any change of tool or model.
And keep the fundamentals in view. The best prompt in the world can't rescue a task nobody has thought through, and a clear-thinking developer with a plain prompt will usually beat a vague one with clever wording. Prompting is a way of expressing your engineering judgement to a tool, not a substitute for it.
Frequently asked questions
How do I write better prompts for AI code generation?
Include the goal and why it matters, the relevant files and conventions, constraints on what must not change, a clear definition of done such as tests that should pass, and the output format you want. Ask for a plan first on larger tasks, show an example of the style you want, and work in small, reviewable steps.
Should I ask an AI assistant for a plan before code?
Yes, for anything beyond a small edit. Reviewing a plan takes seconds and lets you correct a wrong approach, an unnecessary dependency or a risky change before hundreds of lines of code are written. Many coding tools have a planning mode for exactly this.
What is a project instruction file for AI coding tools?
It's a file in your repository that the assistant reads automatically on every request, containing commands to install, test and lint, project conventions and rules such as not modifying tests. Tools name it differently, such as CLAUDE.md for Claude Code, rules files for Cursor and repository instructions for GitHub Copilot.
Why does my AI assistant ignore my existing code patterns?
Usually because it doesn't know about them. Point it to an existing example to follow, name the helpers it should use, and record important conventions in your project instruction file so they apply to every session.
Do I need special keywords or tricks to prompt AI coding tools?
No. Current assistants respond best to clear, specific instructions with good context, much like a capable colleague would. Precise goals, relevant files, constraints and a definition of done matter far more than particular phrasing.
The takeaway
Prompting a coding assistant well is mostly writing a good ticket: a clear goal, the right context, firm constraints and a checkable definition of done. Plan before coding, show examples, iterate in small steps, and move anything you repeat into project instructions. The assistant does the typing; you still own the thinking, and the results show it.
Treat every disappointing result as information: usually it points to missing context, an unclear goal or a task that was too large, and each of those is easy to fix next time. Small improvements in how you ask add up quickly across hundreds of requests.
Author at LuminaryEra
The LuminaryEra editorial desk publishes long-form, hands-on guides on AI-assisted development, large language models, developer tools and web engineering. Articles are researched and drafted with the help of AI tools, link to their sources, and are corrected when readers report errors.
View all articles


