How to Write AI Prompts for Code: A Developer's Practical Guide
Dev prompt patterns for GPT-5.5 and Claude Opus 4.8 — stack context, diff-only output, test-first requests, and copy-paste templates for review, debug, and refactor.
Generate optimized prompts for ChatGPT, Claude & more
Free prompt generator — no account needed.
Try Prompt Generator →Developers paste 400 lines into ChatGPT, ask fix this, and get a full file rewrite that drops error handling and breaks imports. The model wasn't wrong — the prompt asked for a rewrite.
Code prompts in 2026 need stack context, boundary rules, and output shape constraints. Claude Opus 4.8 leads SWE-bench-style tasks; GPT-5.5 leads multi-tool agent loops. Same principles, different interfaces.
This guide is copy-paste practical: the dev prompt stack, six core templates, before/after weak prompts, output format cheat sheet, model routing, and FAQ.
Before vs after: the fix-this trap
Weak prompt:
Here is my React component. Fix the bug.
[400 lines pasted]
Typical output: entire file rewritten, imports reordered, useEffect dependency array changed unrelated to bug, no explanation of root cause, diff unusable.
Strong prompt:
Stack: TypeScript 5.4, React 19, Next.js 15 App Router
TASK: Fix bug below. Output ONLY unified diff — no full file rewrites.
BUG: Submit button stays disabled after valid form — repro: fill all fields, blur email, button never enables
FILES IN SCOPE: src/components/SignupForm.tsx
DO NOT MODIFY: validation schema, API route, other components
TESTS: npm test -- SignupForm.test.tsx must pass
If root cause outside scope, explain in 3 sentences — do not patch unrelated code.
Expected output: 5–15 line diff touching isFormValid logic, hypothesis stated, no collateral changes.
The dev prompt stack
- Stack context — language, framework, version, constraints
- Scope boundary — which files/functions may change
- Output format — diff-only, patch, or single function
- Verification — tests to pass, repro steps, types to satisfy
- Stop rules — when to ask instead of guess
Missing layer 3 is why AI refactors destroy your git history.
Stack context block (paste every time)
Stack: TypeScript 5.4, Next.js 15 App Router, React 19
Package manager: npm
Test runner: Vitest
Style: ESLint + Prettier project defaults
Constraints: No new dependencies without asking. No default exports in new files.
Adjust per project. Static context belongs in Custom GPT / Claude Project instructions.
Template 1 — Bug fix (minimal diff)
TASK: Fix the bug described below. Output ONLY a unified diff — no full file rewrites.
BUG: [symptoms + repro steps]
FILES IN SCOPE: [path/to/file.ts]
DO NOT MODIFY: [other files]
TESTS: npm test -- [test file] must pass
If root cause is outside scope, explain in 3 sentences — do not patch unrelated code.
Claude Opus 4.8 and GPT-5.5 both obey diff-only requests when scope is explicit.
Worked example output: diff shows 3-line change to null check in parseDate(), comment explains timezone edge case, no import changes.
Template 2 — Code review
ROLE: Senior [language] reviewer.
TASK: Review PR diff below.
FOCUS: [security / performance / correctness / API design]
OUTPUT FORMAT:
- Summary (2 sentences)
- Blocking issues (must fix before merge)
- Suggestions (optional)
- Questions for author
Do not rewrite code unless blocking. Reference line numbers from diff.
[paste diff]
Example output description: Summary flags missing input validation on line 47. Blocking: SQL injection vector in raw query builder. Suggestions: extract magic number to constant.
Template 3 — Write tests first
TASK: Write Vitest tests for [function/module] BEFORE implementation.
BEHAVIOR SPEC:
- [case 1]
- [case 2 edge case]
- [error case]
OUTPUT: test file only. No implementation yet.
After tests: separate prompt for implementation that must pass these tests.
Test-first prompts reduce hallucinated happy-path code.
Worked example: tests cover empty input, max boundary, unicode slug, and 403 from upstream API — implementation prompt references test file path explicitly.
Template 4 — Refactor with behavior lock
TASK: Refactor [function/class] for [readability/performance].
BEHAVIOR LOCK: Public API unchanged. All existing tests must pass unchanged.
OUTPUT: diff only. List any behavior you had to change — should be empty.
SCOPE: [single file]
Example: extract nested callbacks to named functions — diff only, zero signature changes, empty behavior-change list.
Template 5 — Explain unfamiliar code
TASK: Explain this code for a new team member.
OUTPUT:
- Purpose (2 sentences)
- Data flow (numbered steps)
- Non-obvious gotchas (bullets)
- Dependencies on other modules
Do not suggest improvements unless I ask.
Use when onboarding or reviewing legacy — not when you want a refactor disguised as explanation.
Template 6 — Migration / upgrade
TASK: Migrate [component] from [A] to [B] per official migration guide.
CONTEXT: [version from → to]
OUTPUT: Step-by-step plan first. Wait for my approval before generating code.
Flag breaking changes with severity.
Example: Next.js 14 → 15 async request API — plan lists 4 files, flags cookies() now async as breaking, waits for go-ahead.
Template 7 — Debug with hypothesis ranking
TASK: Debug issue below. Do NOT write fix code yet.
SYMPTOM: [what breaks]
REPRO: [steps]
LOGS/ERRORS: [paste]
OUTPUT:
- Ranked hypotheses (most likely first, 3–5 items)
- One logging or inspection step per hypothesis
- Which file to inspect first
After I paste results, second prompt for targeted fix with diff-only output.
Prevents shotgun fixes that mask the real bug.
Template 8 — Generate types from API schema
TASK: Generate TypeScript types from OpenAPI fragment below.
RULES: Use interface not type alias. Nullable fields as T | null. Enums as const object + union.
OUTPUT: types file only — path comment at top: src/types/[name].ts
Do not generate fetch client unless asked.
Gemini 3.5 Flash handles large schema fragments fast; Claude Opus 4.8 catches subtle optional/required mismatches.
Output format cheat sheet
| Need | Prompt phrase |
| Minimal change | Output unified diff only |
| New file | Full file with path comment at top |
| Snippet | Function only, no imports unless asked |
| Architecture | Markdown plan, no code until approved |
| Debug | Hypothesis list ranked by likelihood, then targeted logging |
| Review | Structured sections, no rewrite unless blocking |
State output format in the first 3 lines of every dev prompt — models weight early instructions.
Scope boundary table
| Scenario | FILES IN SCOPE | DO NOT MODIFY |
| Single bug | One file | Rest of repo |
| Cross-module fix | 2–3 named paths | Everything else |
| Refactor | One module dir | Public API surface |
| Test add | test file + source under test | Production config |
Vague scope is the top cause of AI breaking unrelated files.
Worked before/after: refactor request
Weak:
Clean up this function and make it faster.
[paste 80-line function]
Output: rewritten algorithm with different edge behavior, new helper file, removed comments.
Strong (template 4):
TASK: Refactor calculateDiscount for readability.
BEHAVIOR LOCK: Public API unchanged. All tests in pricing.test.ts pass.
OUTPUT: diff only. List behavior changes — should be empty.
SCOPE: src/lib/pricing.ts only
Output: extract two pure functions, same outputs for all test cases, 40-line diff, empty behavior-change list.
Worked before/after: code review
Weak:
Review my code.
[entire file, no diff context]
Output: generic style nitpicks, misses auth bypass, suggests rewrite.
Strong (template 2):
ROLE: Senior TypeScript reviewer.
TASK: Review PR diff below.
FOCUS: security, correctness
OUTPUT FORMAT: Summary, Blocking, Suggestions, Questions
Do not rewrite unless blocking.
[unified diff]
Output: flags missing auth check on DELETE route as blocking, cites diff line numbers, no full rewrites.
Agent vs chat prompting
GPT-5.5 in agent mode (Cursor, Claude Code, Codex): put stack context in project rules; each task prompt stays short — scope + output format + repro.
Chat-only (paste code): repeat stack block every message — context does not persist reliably.
Claude Opus 4.8 Projects: upload architecture doc once; per-task prompts reference file paths not full pastes when using tool-enabled IDE.
Model routing for code
Claude Opus 4.8: code review, large codebase Q&A, subtle bug finding, security-sensitive diffs
GPT-5.5: agent workflows, terminal tasks, multi-file with tools, structured codegen pipelines
Gemini 3.1 Pro: repo-scale context when pasting many files, long migration plans
Gemini 3.5 Flash: quick regex, small util snippets, bulk docstring generation, type generation from schema
Hard debug with unclear repro: Claude first. Agent loop with bash/tests: GPT-5.5. Whole-repo read: Gemini 3.1 Pro.
Anti-patterns
Fix this with no repro steps
Paste entire repo without file scope
Accept full-file rewrite when you needed 3-line fix
No mention of test runner
Ask for production secrets in prompt context
Mixing explain and refactor in one prompt
Reviewing whole file instead of diff — model nitpicks old code not in PR
No OUTPUT format line — model chooses prose explanation instead of diff
Common mistakes
Assuming the model remembers stack from last message — repeat stack block
FILES IN SCOPE: entire project — equivalent to no scope
Skipping BEHAVIOR LOCK on refactors — silent semantic changes ship
Asking for fix and tests in one prompt — tests match wrong behavior
Pasting minified or transpiled output instead of source
Trusting AI-generated migration without reading breaking-change flags
Security rules for dev prompts
Never paste: API keys, prod DB URLs, customer PII, signing secrets
Use placeholders: [REDACTED_KEY], sanitize logs before paste
Add: Do not suggest logging secrets or PII to stdout
For security review FOCUS: include OWASP top 10 checklist reference
PromptMake workflow
/text → describe bug + stack → generate scoped dev prompt → paste output into Claude Code / Cursor / ChatGPT.
Save stack context block as snippet — only change TASK and FILES IN SCOPE per ticket.
FAQ
Diff-only or full file — which default?
Diff-only for any existing file. Full file only for new files with path comment at top.
How much code can I paste?
Chat: 1–2 relevant files. Above that use Gemini 3.1 Pro or IDE agent with repo access. Paste function + 20 lines context, not whole module.
Should I ask the model to run tests?
In agent IDEs yes — include TESTS: [command]. In chat-only, you run tests; model does not see results unless you paste them.
What if the model ignores diff-only?
Reply: Reject. Output unified diff only for files in scope. Repeat FILES IN SCOPE. Switch to Claude Opus 4.8 if GPT keeps rewriting.
Test-first or implementation-first for greenfield?
Test-first (template 3) for logic with edge cases. Implementation-first for UI scaffolding where tests come after visual review.
How do I prompt for performance optimization?
Require benchmark or complexity target: Reduce from O(n²) to O(n log n). Preserve behavior lock. Output diff + before/after complexity note.
Can AI write commit messages from diff?
Yes — separate prompt: TASK: Write conventional commit message for diff below. Max 72 char subject. No body unless breaking change.
Monorepo: how to scope?
FILES IN SCOPE: packages/api/src/handlers/user.ts only. DO NOT MODIFY: packages/web, shared configs. Name package manager and test command for that package.
IDE integration tips
Cursor / Claude Code: put stack context in .cursorrules or CLAUDE.md — per-task prompts only need TASK, BUG, FILES IN SCOPE.
GitHub Copilot Chat: prefix with #file references instead of pasting — reduces context noise.
When agent has terminal access, add: Run [test command] after patch and report pass/fail before finishing.
Separate planning prompt from execution prompt on migrations — approval gate prevents half-applied upgrades.
Related articles
Claude vs ChatGPT vs Gemini — route coding tasks by model
Structured output prompting — JSON schemas for codegen pipelines
Reasoning models prompting — when to drop CoT on hard debug
System prompt for ChatGPT — project-level dev context
Bottom line
Dev prompts are stack + scope + output shape + tests. Say diff-only. Name files in scope. Lock behavior on refactors. The model can write good code — your prompt decides whether you get a patch or a grenade.
Ready to generate your own prompts?
Free. No sign-up required. Works with all major AI models.