AI coding agents are only as good as the prompts you give them. Whether you're using GitHub Copilot, Cursor, or the OpenAI API, these five patterns will help you get precise, actionable results.
// The goal: a reusable, predictable AI coding agent
// that can refactor, explain, and test code.
1. Role and Context Anchoring
Start your prompt with a clear system message that defines the agent's role, the project, and any constraints. This sets the tone for every response.
System: You are a senior Python developer working on a
FastAPI project. You follow PEP 8, write type hints,
and prefer functional patterns. Keep all changes
backwards compatible.
2. Few-Shot Examples
Show, don't tell. Give the agent one or two concrete examples of the desired output format and style.
User: Refactor this function to add error handling.
Example transformation:
Before:
def parse(data):
return data['value']
After:
def parse(data) -> int | None:
try:
return data['value']
except KeyError:
print('Missing value')
return None
Now refactor:
# Your code here...
Few-shot prompts reduce guesswork. Keep examples small but representative.
3. Structured Output for Parsing
When you need to consume the agent's response automatically, ask for JSON.
User: Analyze this code and return JSON only with these
fields:
{"severity": "low|medium|high", "issue": "what broke",
"suggestion": "fix"}
Code:
function add(a, b) { return a + b; }
# Parse it in your CI/CD pipeline
def parse_ai_response(raw: str) -> dict:
return json.loads(raw)
4. Chain-of-Thought
Ask the agent to reason step by step before giving the final answer. This dramatically improves handling of complex refactors.
User: Refactor this React component to use hooks.
Let's think step by step.
First, identify the state. Then, replace lifecycle
methods. Finally, write the new component.
5. Self-Review Loop
Have the agent critique its own output. This catches logical errors that a single pass misses.
User: Now review your response. Are there any edge
cases or bugs? If so, provide an improved version.
Combine Them All
Don't pick just one. A reliable agent pipeline looks like this:
1. System message: role + context
2. Few-shot: show your coding style
3. Ask for JSON output
4. Request step-by-step reasoning
5. Then: "Review and improve your answer"
Start with these patterns today. Your prompts—and your agents—will be dramatically better.
The self-review pattern is interesting, but I wonder how it handles edge cases when the model just repeats its own mistakes. Does it actually catch logical bugs?