AI coding

Prompting Patterns That Make Coding Agents Reliable

Antonio Evans7 min read

A developer lays a clear path of stepping stones across a stream, and a small robot hops along them one at a time without slipping.
Key points

Key points

  1. 1A reliable coding prompt names the action, the exact place in the code, the constraints and the check that proves the work is done.
  2. 2Explaining why a rule exists lets the agent apply it to cases you did not list, and pointing to files beats describing them.
  3. 3Separate requests to investigate from requests to change code, and say which actions need confirmation, so the agent neither stalls nor overreaches.
  4. 4For long work, keep the plan, progress and test status in files and git rather than in the conversation, and write each rule once in calm language.

Why the prompt matters more for an agent

A chat assistant answers and stops. A coding agent reads files, edits them, runs commands and keeps going. A vague prompt to a chat model wastes one reply. A vague prompt to an agent can produce a large, confident change in the wrong place.

The team at Tweag ran an internal experiment with coding agents and wrote up what they learned in their agentic coding handbook. Their finding: "prompt quality was one of the most critical success factors. Good prompts led to clean, scalable code. Vague or overly broad prompts caused hallucinations, bugs, and wasted time" (Tweag).

Anthropic's prompting guide offers a test that works for any model: "Show your prompt to a colleague with minimal context on the task and ask them to follow it. If they'd be confused, Claude will be too" (Claude prompting best practices). The same guide suggests thinking of the model as "a brilliant but new employee who lacks context on your norms and workflows."

The patterns below are what that new employee needs. None of them depend on a particular model or tool, which is why they keep working as the tools change.

State the action, the target and the finish line

Every task prompt should answer three questions: what to do, where to do it, and how to know it is done.

Tweag's first tip is to "start prompts with a clear action, expected output, and any important constraints," and its second is to "specify the exact file, service, or component where the change should happen" (Tweag). Their examples make the difference concrete:

Weak promptStrong prompt
"Add login functionality.""Create a POST /users/login endpoint using NestJS. It should accept email and password, validate input, and return a JWT if credentials are correct."
"Finish all validations for the signup flow.""Add email format validation to the user registration form in RegisterForm.tsx."

The verb matters more than people expect. Anthropic's guide notes that if you ask "can you suggest some changes," the model "will sometimes provide suggestions rather than implementing them." If you want edits, say "Change this function to improve its performance" (Claude prompting best practices).

The finish line is the part most prompts leave out. "Done when pnpm test src/auth passes and the endpoint returns 401 for a wrong password" turns an open-ended request into one the agent can check for itself.

OpenAI's practical guide to building agents gives two more rules that apply directly to task prompts. "Define clear actions": every step should correspond to a specific action or output. And "capture edge cases": anticipate decision points, such as missing information, and say what to do when they occur (OpenAI agents guide). For a coding task, that usually means one line on what to do if the expected file, function or test does not exist.

Keep each prompt to one task. Tweag's handbook advises breaking "large features into small, independent prompts whenever possible," and calls the broad version "likely to produce incomplete or scattered results."

Give context and the reason behind each rule

A bare rule covers the cases you thought of. A rule with a reason covers the cases you did not.

Anthropic's guide shows this with a small example. "NEVER use ellipses" is less effective than explaining that the response "will be read aloud by a text-to-speech engine, so never use ellipses since the text-to-speech engine will not know how to pronounce them." The guide adds that the model "is smart enough to generalize from the explanation" (Claude prompting best practices). Tweag reports the same effect for architecture: describing the "why" behind a feature "improves AI's architectural decisions."

In coding terms:

  • Weak: "Do not use the ORM in the reports module."
  • Strong: "Do not use the ORM in the reports module. The report queries run against a read replica with hand-tuned SQL, and the ORM generates joins that time out there."

The second version tells the agent what to do when it meets a related case, such as a new report or a different query builder.

For context about the code itself, point rather than paste. Anthropic's engineering team describes agents that keep "lightweight identifiers (file paths, stored queries, web links, etc.)" and load the content when they need it (Anthropic engineering). Naming src/auth/session.ts and an example file to follow is usually better than pasting both, because the agent can read the current version and nearby code. Paste only what the agent cannot reach: an error message, terminal output or a snippet from a ticket.

Examples are the strongest form of context. Anthropic's guide calls them "one of the most reliable ways to steer" output and asks that they be relevant, diverse and clearly marked off from the instructions. In a codebase, the best example is usually an existing file: "Follow the structure of handlers/orders.ts."

Separate looking from doing

Many bad agent sessions start with a question that the agent treated as an order, or an order that the agent treated as a question. Make the mode explicit.

OpenAI's guidance for its models includes a compact policy for exactly this (OpenAI model guide):

For requests to answer, explain, review, diagnose, or plan, inspect the relevant
materials and report the result. Do not implement changes unless the request also
asks for them.

For requests to change, build, or fix, make the requested in-scope local changes
and run relevant non-destructive validation without asking first.

Require confirmation for external writes, destructive actions, purchases, or a
material expansion of scope.

Anthropic's guide offers matching prompts for both directions: one that makes the model "implement changes rather than only suggesting them," and one that tells it not to "jump into implementation or change files unless clearly instructed" (Claude prompting best practices). Pick the default that fits how you work and put it in your project context file, so you do not repeat it in every prompt.

For anything larger than a small fix, use the separation deliberately. First ask the agent to read the relevant code and write a plan without editing anything. Review the plan. Then ask it to implement the plan. The review step is cheap, and it catches wrong assumptions before they turn into code.

Also tell the agent when an ambiguity should stop it. OpenAI's guide advises giving the model "domain context, hard constraints, approval boundaries, and success criteria" and telling it "when an important ambiguity should trigger a question." Without that line, some agents guess and some stop to ask about trivia.

Make verification part of the task

An agent that cannot check its work will report success on the strength of its own confidence. Put the check in the prompt.

OpenAI's guide for coding agents says to "require thorough testing for correctness" and gives a reason that applies to any tool: patches should be validated carefully, because an edit tool "may return 'Done' even on failure" (OpenAI prompt engineering). Anthropic's guide lists verification tools as a requirement for longer autonomous work, "as the length of autonomous tasks grows," including browser tools for verifying user interface changes (Claude prompting best practices).

A verification clause names the exact commands and the expected result:

Verify before you report done:
1. Run `pnpm test src/billing` and `pnpm typecheck`. Both must pass.
2. Start the dev server and request GET /invoices/123 as a non-owner.
   It must return 403.
3. Report the commands you ran and their output.

Protect the tests while you are at it. Anthropic's guide suggests stating plainly: "It is unacceptable to remove or edit tests because this could lead to missing or buggy functionality." Agents under pressure to go green will otherwise sometimes change the test instead of the code.

Asking for the output, not just the claim, is the important part. "Tests pass" is a statement. The pasted test summary is evidence.

Set boundaries for risky actions

Agents act. Some actions are easy to undo, such as editing a file in a working tree. Others are not, such as force-pushing, dropping a table or posting to a shared channel. A reliable prompt says which is which.

Anthropic's guide offers a prompt worth adapting (Claude prompting best practices):

Consider the reversibility and potential impact of your actions. You are
encouraged to take local, reversible actions like editing files or running tests,
but for actions that are hard to reverse, affect shared systems, or could be
destructive, ask the user before proceeding.

The same guide lists examples that warrant confirmation: deleting files or branches, dropping database tables, git push --force, git reset --hard, pushing code, commenting on pull requests and modifying shared infrastructure. It adds an instruction that prevents a common shortcut: "do not use destructive actions as a shortcut," for example by bypassing safety checks with --no-verify or discarding unfamiliar files that may be someone's work in progress.

Prompts are guidance, not enforcement. Back the most dangerous boundaries with tool permissions, protected branches and credentials scoped to what the task needs.

Keep long work on track with files, not memory

A long task will outgrow a single conversation. The agent's context fills up, older details fade, and work gets repeated or dropped. The fix is to keep the state of the work somewhere the agent can reread.

Anthropic's guide describes a pattern for tasks that span several context windows (Claude prompting best practices):

  • Use the first session to set up. Write the tests and setup scripts first, then use later sessions to work through a task list.
  • Track test status in a structured file, such as a tests.json with each test marked passing, failing or not started.
  • Keep free-form progress notes in a text file: what was done, what is next, what to watch out for.
  • Use git as the log. The guide notes that git "provides a log of what's been done and checkpoints that can be restored."
  • Start fresh sessions with explicit orientation, such as "Review progress.txt, tests.json, and the git logs."

This has a useful side effect. Because the state lives in files, any session, any agent or any person can pick up the work. A prompt for a resumed session becomes short: read the notes, run the tests, continue with the next unchecked item.

Write each rule once, calmly

Two habits that feel like they help often hurt: shouting and repetition.

Anthropic's guide notes that recent models are more responsive to instructions than earlier ones, so prompts written to overcome old under-triggering "may now overtrigger." Its advice is to "dial back any aggressive language": where you might have written "CRITICAL: You MUST use this tool when...", write "Use this tool when..." (Claude prompting best practices).

OpenAI's guide makes the matching point about repetition: "Keep the policy in one place and state each rule once." Repeating "ask first" or "do not mutate" in several places "can cause unnecessary approval requests for safe, expected actions" (OpenAI model guide). The same guide warns that "unclear or conflicting guidance in a skill file may cause the model to pause and block work early," and recommends stating which source wins when a user's instruction and a skill disagree.

Put together, a reliable task prompt looks like this:

Task: Add rate limiting to POST /auth/login.
Where: src/auth/routes.ts. Follow the pattern in src/payments/routes.ts,
which already uses the rateLimit middleware.
Why: we see credential-stuffing attempts; limit by IP and by email.
Constraints: no new dependencies; do not change the response body for
successful logins.
Done when: a test shows the 6th attempt in a minute returns 429,
`pnpm test src/auth` and `pnpm lint` pass, and you paste their output.
Stop and ask if: the change needs a database migration.

It names the action, the place, the example to follow, the reason, the limits, the finish line and the stop condition. Each appears once. That is most of what reliability takes.

FAQ

FAQ

Do these patterns depend on which model or tool I use?

No. They come from vendor guidance and practitioner experience across several tools, and they describe what any capable new teammate would need. Model-specific tuning, such as how much to encourage tool use, changes over time, so keep it in one place and revisit it.

Should I write prompts in Markdown or XML?

Either works for structure. OpenAI's prompt engineering guide recommends Markdown headers and lists for sections and XML tags to mark where reference content begins and ends. What matters more is that instructions, context and examples are clearly separated.

How long should a task prompt be?

Long enough to name the action, the location, the constraints and the check, and no longer. Most good task prompts fit in ten lines because project-wide rules live in the context file. If a prompt keeps growing, the task is probably too big and should be split.

What should I do when the agent produces the wrong thing?

Fix the prompt, not the output. Tweag's handbook advises refining the original prompt instead of manually patching a bad result, because the improved prompt helps the next run too. If the same mistake recurs across tasks, add a rule to the project context file.

Is it worth asking the agent to plan before coding?

Yes, for anything beyond a small fix. A plan written to a file costs little and lets you catch wrong assumptions before code exists. For one-line changes, skip it and go straight to a clear task prompt with a check.

Sources

Sources

  1. https://tweag.github.io/agentic-coding-handbook/PROMPT_ENGINEERING/
  2. https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices
  3. https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
  4. https://developers.openai.com/api/docs/guides/latest-model
  5. https://developers.openai.com/api/docs/guides/prompt-engineering
  6. https://openai.com/business/guides-and-resources/a-practical-guide-to-building-ai-agents/
About the author

About the author

Antonio Evans
Antonio Evans

Antonio Evans is the founder of Quanta Intelligence and a fractional CTO who builds HIPAA-ready AI systems for health and life-science companies. Before that he was technical co-founder of FriendsEAT for twenty years, CEO of Socialdraft, and a data engineer at IBM. Antonio lives with his dog Santino in Lisbon, Portugal.

All articles