CoreMesh

Prompts for Coding: Copy-Paste Templates and Why They Work

Copy-paste prompts for debugging, tests, refactors and code review that work in Claude, ChatGPT and Gemini, with the reasoning behind each line.

Prompts for Coding: Copy-Paste Templates and Why They Work

Good prompts for coding share four parts: the goal, the code and error, the constraints, and a definition of done. "Fix this" fails because the model has to guess all four. "This function raises ValueError on prices with commas, here's the function and the traceback, keep the signature, make the attached test pass" works about equally well in Claude, ChatGPT and Gemini.

Below are copy-paste prompts for debugging, writing tests, refactoring and code review, with the reasoning behind each line. The reasoning is the useful part. Once you know why a sentence is there, you can drop it when it doesn't apply and write your own.

The four parts of a prompt for coding#

Every template on this page is the same skeleton with different wording.

Part Question it answers Example
Goal What should be different when you're done? Make parse_price accept thousands separators
Context What does the model need to see? The function, the traceback, the Python version
Constraints What must not change? Keep the signature. Don't touch other files.
Done How will you check the result? The tests in test_prices.py pass unchanged

Anthropic's Claude prompting best practices recommend wrapping each kind of content in its own XML tag, such as <instructions>, <context> and <input>, so the model doesn't confuse your instructions with the code you pasted. The same page says a single role sentence in the system prompt changes behavior, and its example is as short as "You are a helpful coding assistant specializing in Python." Google's prompt design strategies for Gemini say Gemini 3 responds best to prompts that are direct, well structured, and clearly define the task and its constraints. Different vendors, same shape. The general techniques behind this are covered in prompt engineering techniques that work in any AI chat.

If you send the same kind of prompt often, build it from parts instead of retyping it. This script assembles a debugging prompt so you can't forget a section:

python
# Assemble a debugging prompt from parts so nothing gets forgotten.
parts = {
    "context": "Runtime: Python 3.12\nExpected: parse_price('1,299.00') -> 1299.0\nActual: ValueError",
    "error": "ValueError: could not convert string to float: '1,299.00'",
    "code": "def parse_price(s):\n    return float(s)",
    "instructions": (
        "1. State the root cause before proposing a change.\n"
        "2. Propose the minimal fix; keep the signature.\n"
        "3. Show one test that verifies the fix."
    ),
}

role = "You are a senior Python engineer debugging a production issue."
blocks = [f"<{tag}>\n{body}\n</{tag}>" for tag, body in parts.items()]
prompt = role + "\n\n" + "\n\n".join(blocks)

print(prompt)
print()
print(f"{len(prompt.split())} words, {len(blocks)} tagged sections")

Debugging prompts#

Debugging is where vague prompts cost the most, because the model will happily fix a symptom. This template forces a diagnosis first.

text
You are a senior [LANGUAGE] engineer debugging a production issue.

<context>
Runtime: [LANGUAGE AND VERSION], [FRAMEWORK AND VERSION]
Expected: [WHAT SHOULD HAPPEN]
Actual: [WHAT HAPPENS INSTEAD]
</context>

<error>
[FULL ERROR OR TRACEBACK]
</error>

<code>
[THE SMALLEST CODE THAT REPRODUCES IT]
</code>

<instructions>
1. State the root cause in one or two sentences before proposing any change.
2. Do not speculate about code you have not seen. If you need another file, ask for it by name.
3. Propose the minimal fix. Do not refactor surrounding code.
4. Explain how to verify the fix with a test or a command.
</instructions>

Why it's worded that way:

  • The role line is one sentence because Anthropic's docs say that's enough to shift tone and focus. Longer personas don't add much.
  • Expected versus actual comes before the traceback. The traceback tells the model where it broke, not what you wanted.
  • "State the root cause before proposing any change" stops the model from patching the line in the stack trace when the real bug is three calls up.
  • "Do not speculate about code you have not seen" is adapted from Anthropic's hallucination guidance for agentic coding, which tells Claude never to make claims about code it hasn't opened. In a chat, the equivalent is asking for the file by name.
  • "Minimal fix, no refactor" is there because Anthropic documents that some Claude versions tend to overengineer, and the same thing happens in other models. Saying it costs you one line.
  • The verification step is the self-check pattern from the same page: "Before you finish, verify your answer against [test criteria]." Anthropic notes that Claude Opus 5 already verifies well and that extra verification instructions can make it over-verify. For other models, keep the line.

Paste the smallest code that reproduces the problem, not the whole module. If you can't isolate it, say so and paste the entry point plus the failing function.

Prompts for writing tests#

The failure mode here is the opposite of debugging. Models write tests enthusiastically and then edit the code until the tests pass. This template blocks that.

text
Write unit tests for the code below using [TEST FRAMEWORK].

<code>
[FUNCTION OR MODULE]
</code>

<requirements>
- Cover the normal path, each boundary ([EMPTY INPUT, MAX SIZE, ...]), and each error the code raises.
- One behavior per test. Name tests test_[unit]_[condition]_[expected].
- Do not change the code under test. If you believe it has a bug, add a failing test and explain it in a comment instead of fixing the code.
- Do not mock anything except [NETWORK, CLOCK, FILESYSTEM].
</requirements>

Here is one existing test to match in style:
<example>
[ONE EXISTING TEST]
</example>

Why:

  • Listing the boundaries yourself gets you tests for cases you care about instead of five variations of the happy path.
  • "One behavior per test" plus a naming pattern gives you tests you can still read six months later.
  • "Do not change the code under test" matters because the Anthropic guide documents that Claude can focus on making tests pass at the expense of general solutions. Their suggested wording for agents, "tests are there to verify correctness, not to define the solution," is the same idea from the other side. Asking for a failing test plus a comment when the model suspects a bug keeps the decision with you.
  • The mocking rule stops the model from mocking the very function you're testing.
  • The one existing test is a few-shot example. Google's Gemini docs recommend always including examples and keeping their formatting consistent, because the main thing examples teach is format. One well-chosen test is usually enough. How few-shot prompting works and how many examples to use covers when to add more and when it starts to overfit.

Refactoring prompts#

Refactors go wrong when the goal is fuzzy. "Clean this up" produces renamed variables and a new abstraction nobody asked for.

text
Refactor the code below. Goal: [ONE SPECIFIC GOAL, e.g. remove the duplicated retry logic].

<code>
[CODE]
</code>

<rules>
- Behavior must not change. The existing tests in [TEST FILE] must pass unchanged.
- Keep the public signatures of [FUNCTIONS OR CLASSES] exactly as they are.
- Don't add docstrings, comments, type annotations or error handling to code you didn't otherwise change.
- Don't introduce helpers or abstractions for one-time operations.
- Return the full refactored file, then a short list of what changed and why.
</rules>

Why:

  • One goal per prompt. If you want two refactors, send two prompts, or chain them so the output of the first is the input of the second. Both the Anthropic and Google docs describe chaining as the way to handle multistep work you want to inspect between steps.
  • "Tests must pass unchanged" is the behavior contract. Without it the model will "fix" a test that the refactor broke.
  • The rules about docstrings, comments, type annotations, error handling and one-off abstractions are lifted almost verbatim from Anthropic's sample prompt for reducing overengineering. They work in other models too because they're concrete.
  • "Return the full file" avoids the "rest of file unchanged" fragments you then have to merge by hand. For large files, ask for a unified diff instead.

How to prompt for code review#

Review prompts need a priority order and an output format, or you get forty nits and no mention of the SQL injection.

text
Review this diff as a [SENIOR BACKEND ENGINEER] would in a pull request.

<diff>
[DIFF OUTPUT]
</diff>

<focus>
Look for, in this order: correctness bugs, security issues at system boundaries, missing error handling for things that can actually happen, and test gaps.
Ignore formatting and naming unless it hides a bug.
</focus>

<format>
For each finding: file and line, severity (blocker / should-fix / nit), what breaks and the concrete input that breaks it, suggested fix.
If you find nothing in a category, say so in one line. Don't pad.
</format>

Why:

  • "As a senior backend engineer would in a pull request" sets the role and the register. You get review comments, not an essay.
  • The ordered focus list tells the model what matters. Putting formatting last and marking it ignorable is the single biggest quality improvement for review prompts.
  • "Error handling for things that can actually happen" echoes Anthropic's advice to validate at system boundaries and trust internal code. It keeps the review from demanding null checks on every line.
  • "The concrete input that breaks it" forces evidence. A finding without a failing input is usually speculation, and it's easy for you to dismiss or verify.
  • Severity labels and "don't pad" make the output scannable and stop the model from inventing findings to fill space.

Paste a diff against your base branch; the git diff documentation lists the options for producing one. Before you send any template, check that you filled every placeholder. This does it for you:

javascript
// Find placeholders you forgot to fill before sending a template.
const template = `Review this diff as a [SENIOR BACKEND ENGINEER] would.
<diff>
-    return float(s)
+    return float(s.replace(",", ""))
</diff>
Focus on [FOCUS AREAS]. Ignore formatting.`;

const unfilled = [...template.matchAll(/\[([A-Z][A-Z /,.'-]*)\]/g)].map(m => m[0]);

if (unfilled.length) {
  console.log("Unfilled placeholders:", unfilled.join(", "));
} else {
  console.log("Template is ready to send.");
}

Prompting Claude, ChatGPT and Gemini differently#

The templates above are model-neutral. A few adjustments come from the vendors' own docs.

Claude. XML tags and a short role are the documented structure. For hard problems, Anthropic recommends general instructions like "think thoroughly" over a hand-written step-by-step plan, because the model's own reasoning often beats the plan. On Claude Fable 5.1, Claude Fable 5, Claude Opus 5.5, Claude Opus 5 and Claude Sonnet 5.5, don't ask the model to write out its reasoning in <thinking> tags. Anthropic says such a request may be declined; rely on the built-in thinking instead, at a lower effort level if latency matters. If you use Claude Opus 5, remove explicit "verify your work" lines, since Anthropic reports it over-verifies with them.

Gemini. Google's docs lean harder on examples. They recommend always including few-shot examples and warn that too many can overfit the response to them. Two Gemini-specific tricks help with code. First, the completion strategy: end your prompt with the start of the answer you want, such as the first line of a test file, and the model continues the pattern. Second, for repeatable output such as generating fixtures, a temperature of 0 is deterministic according to the same page. Gemini 4 Argon prompting tips has templates tuned for the current Gemini generation.

ChatGPT. The four-part structure carries over without changes, and the test, refactor and review templates work as written. Explicit constraints and a stated output format do most of the work in every chat model.

Prompts for vibe coding and coding agents#

Vibe coding, where you describe what you want and accept what comes back, is prompting with the context and constraints removed. That's fine for throwaway prototypes. When it stops being fine, add the parts back one at a time, starting with "done".

Two wordings from the Anthropic guide are useful dials. When you want more, their example replaces "Create an analytics dashboard" with "Create an analytics dashboard. Include as many relevant features and interactions as possible. Go beyond the basics to create a fully-featured implementation." When you want less, use the overengineering rules from the refactor template. Most vibe coding sessions want the first prompt on day one and the second from day two onward.

For agents that run tools and edit files, the stakes are higher because nobody reads the intermediate output. Three lines from the Anthropic docs belong in nearly every agent prompt:

text
Implement a solution that works correctly for all valid inputs, not just the test cases. Do not hard-code values or create solutions that only work for specific test inputs.

If the task is unreasonable or infeasible, or if any of the tests are incorrect, please inform me rather than working around them.

If you create any temporary new files, scripts, or helper files for iteration, clean up these files by removing them at the end of the task.

The first stops test-gaming. The second gives the agent permission to stop instead of hacking around a broken test. The third exists because Anthropic documents that recent models use scratch files, especially Python scripts, as a working area, which helps results but leaves clutter. Rules like these belong in a persistent system prompt rather than in every message; system prompt examples for coding and support shows how to lay one out.

For bigger tasks, chain: one prompt to produce a plan, one to implement it, one to review the diff against the plan. Anthropic describes this draft, review, refine loop as the most common chaining pattern, and Google's docs describe the same sequential chaining with each output feeding the next.

Common mistakes in coding prompts#

  • Describing the error instead of pasting it. "It throws some kind of type error" loses the line number, the type and the call stack. Paste the whole traceback.
  • No definition of done. Without "the tests in X pass" or "the endpoint returns 201 on this payload," the model decides when it's finished, and it decides early.
  • Forgetting the negative constraints. "Don't change the signature" and "don't touch other files" prevent most of the collateral damage. Models default to helpfulness, which in code means touching things.
  • Missing versions. Python 3.12 versus 3.8, or React class components versus hooks, changes the right answer. One line of context saves a round trip.
  • Letting the model edit the tests. If the tests are the spec, say they can't change. If a test is wrong, ask for a report, not a patch.
  • Asking new Claude models for visible reasoning tags. Anthropic says this may be declined on Fable 5.1, Fable 5, Opus 5.5, Opus 5 and Sonnet 5.5. Lean on built-in thinking instead.
  • Piling on examples. Google's docs warn that too many few-shot examples overfit. One or two consistent ones usually beat eight.
  • One mega-prompt for a multistep task. Plan, implement and review in separate turns so you can check each step.

Quick reference#

Before sending a coding prompt, check:

  1. Goal in one sentence, with the file or function named.
  2. Code pasted, smallest reproducing version, inside its own tag or fence.
  3. Full error or traceback, verbatim.
  4. Language, framework and versions.
  5. What must not change: signatures, other files, tests.
  6. Definition of done: tests, a command, or an input and its expected output.
  7. Output format: full file, diff, or list of findings with severity.
  8. One example if format matters (tests, commit messages, review comments).
  9. For agents: general solution, report broken tests, clean up temp files.
  10. Every [PLACEHOLDER] filled.

Quick answers

What are the best prompts for coding in ChatGPT?

The same four-part structure works: goal, pasted code and error, constraints, and a definition of done. The debugging, test, refactor and review templates above work in ChatGPT as written.

How do I prompt Claude for coding?

Anthropic's docs recommend separating instructions, context and code with XML tags and adding a one-sentence role. Ask for a self-check against your tests, except on Claude Opus 5, and don't request visible reasoning in thinking tags on the newest models.

How do I prompt Gemini for coding?

Google's docs say to always include a few consistently formatted examples and to keep prompts direct and well structured for Gemini 3. You can also end the prompt with the first line of the output you want and let the model complete the pattern.

How do I prompt for code review?

Paste the diff in its own tag, give the model a reviewer role, list what to look for in priority order with formatting last, and require a severity, a concrete failing input and a suggested fix for every finding.

What's a good prompt for vibe coding?

Describe the outcome and how you'll know it works. If you want a richer result, add Anthropic's wording to include as many relevant features as possible and go beyond the basics; as the project grows, add constraints on what must not change.

Did this solve it?

One tap. No account.

Saved you an hour? Send a tip.

USDC or ETH on Base, Ethereum, Arbitrum and more. Keeps the notes free and the examples running.

Base

Network

0xc783bc5c3fa14cEC3f09A22284bC91C5AF0d59e1
Open in wallet · 5 USDC

On a computer? Scan the code with your phone wallet, or copy the address.

Pick the network your wallet or exchange uses. USDC works on all six; ETH on Base, Ethereum, Arbitrum and Optimism. Don't send on Tron or Solana: this address doesn't exist there. Tips are optional and unlock nothing; every guide stays free.

Discussion

Start the discussion

Indra Wijaya

Builds and runs AI agents, bots and content pipelines, and writes down what works and what broke.

About · Email · RSS

Keep reading

New notes, no spam.

One post at a time, only when there's something worth reading. Follow in any feed reader.

Subscribe via RSS