Insight of the Day! detail and precise guide (emphasizement in many example) in making prompt that is easy and friendly to be understood by AI Coding Assistant +STEERING the AI
Of course! Here is a detailed, precise, and example-rich guide to crafting prompts that AI Coding Assistants (like GitHub Copilot, Claude, Cursor, ChatGPT for code) will understand and execute effectively.
The Core Philosophy: "Talk to the AI Like a Junior Developer"
Imagine a brilliant junior developer. They are fast and know a lot, but they lack context, make assumptions, and can't read your mind. Your goal is to provide clarity, context, and constraints.
---
The 4 Pillars of an Effective Coding Prompt
1. Context: What is the environment? (File, framework, language)
2. Task: What do you want to achieve? (Create, fix, modify, explain)
3. Requirements & Constraints: How should it be done? (Specifics, rules, edge cases)
4. Format & Output: What should the final result look like? (Code, list, comment-only)
---
Pillar 1: Context - Set the Stage
The AI doesn't know what file you're in or what project you're working on unless you tell it.
How to provide context:
· Start a comment with the language/framework.
· Mention the file you are in.
· If relevant, reference other parts of your codebase.
Bad Example (No Context):
```python
# Make a function to fetch users.
```
Why it's bad: The AI has to guess everything. From a database? An API? What's the return type?
Good Examples (With Context):
```python
# In a Django model file (models.py), create a function to fetch active users from the database.
```
```javascript
// In this React component (UserProfile.js), using the existing 'api' library, write a function to update the user's email.
```
```python
# File: utils/email_sender.py
# We have an SMTP server configured at `smtp_server`. Write a function to send a welcome email.
```
Why it's good: The AI now knows the language, framework, environment, and even existing variables to use.
---
Pillar 2: Task - Be Specific and Action-Oriented
Use clear, imperative verbs. "Create", "Write", "Fix", "Refactor", "Translate", "Explain".
Bad Example (Vague Task):
```python
# Do something with this list.
```
Why it's bad: "Do something" is meaningless. Sort it? Filter it? Print it? Send it to the moon?
Good Examples (Specific Task):
```python
# Write a function called `filter_even_numbers` that takes a list of integers and returns a new list containing only the even numbers.
```
```javascript
// Refactor this `fetch` call into an async/await function named `getPostData`.
```
```python
# Fix the bug in this function. It's supposed to calculate the factorial, but it returns 0 for any input above 1.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
```
Why it's good: The AI knows the exact action, the intended outcome, and in the last case, has the broken code to analyze.
---
Pillar 3: Requirements & Constraints - The Devil is in the Details
This is the most crucial part for getting precise results. List your specifications.
Types of Constraints:
· Input/Output: Parameter types, return types.
· Behavioral: How it should handle errors, specific algorithms to use, performance considerations.
· Stylistic: Naming conventions, code style (e.g., "use a lambda function").
· Libraries: Specific libraries or functions to use or avoid.
Bad Example (No Constraints):
```python
# Connect to a database.
```
Why it's bad: Which database? PostgreSQL? SQLite? What are the credentials? Using SQLAlchemy or psycopg2?
Good Examples (With Detailed Constraints):
```python
# Write a Python function `safe_divide(a: float, b: float) -> float`.
# Requirements:
# 1. It should return the result of a / b.
# 2. If b is zero, return 0.0 instead of throwing an error.
# 3. Use type hints as shown.
```
```javascript
// Create a React hook `useLocalStorage` for synchronizing state with localStorage.
// Requirements:
// 1. It should take a key (string) and an initial value.
// 2. It returns an array [value, setValue], just like useState.
// 3. On mount, it reads from localStorage. If the key doesn't exist, use the initial value.
// 4. When the value is set via setValue, it should also update localStorage.
```
```python
# Using the `requests` library, write a function to GET data from 'https://api.example.com/data'.
# Constraints:
# 1. Add a timeout of 5 seconds.
# 2. Handle potential `requests.exceptions.Timeout` and `requests.exceptions.ConnectionError`.
# 3. On success, return the JSON response. On failure, return None.
```
Why it's good: The AI has a precise blueprint to follow. It knows about edge cases, error handling, and the exact library to use.
---
Pillar 4: Format & Output - Define the Deliverable
Tell the AI exactly what form you want the answer in.
Common Output Types:
· Code Block: The default. You just want the code.
· Code with Comments: "Write the code and add detailed inline comments."
· Explanation Only: "Explain what this regular expression does: /^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,}$/"
· Step-by-Step Plan: "Give me a step-by-step plan to implement OAuth in my Next.js app before writing code."
Examples:
```python
# Write a Python function to check for a prime number. Output only the code, no explanations.
```
```javascript
// Refactor this Vue.js component to use the Composition API. Please add comments to explain the new syntax compared to the Options API.
```
---
Putting It All Together: The "Perfect Prompt" Template
Combine all four pillars into a single, powerful prompt.
Template:
```
[CONTEXT] In [File/Language/Framework],
[TASK] I need to [Clear Action].
[REQUIREMENTS] The requirements are:
- Requirement 1...
- Requirement 2...
- Constraint 1...
[OUTPUT FORMAT] Please provide [Desired Output Format].
```
Real-World Example Using the Template:
Context: In my Flask application (app.py),
Task: I need to create a new API endpoint at /api/users/<id>.
Requirements:
· It should handle a GET request.
· It fetches the user from the SQLAlchemy User model by the provided id.
· If the user is found, return a JSON object with { "id", "username", "email" } and a 200 status.
· If the user is not found, return a JSON { "error": "User not found" } with a 404 status.
Output Format: Write the complete Python function with the route decorator.
This prompt will almost certainly generate a perfect, production-ready Flask route.
Advanced Techniques & Pro-Tips
1. Iterative Prompting: Don't try to do everything in one go.
· Prompt 1: "Give me a plan to set up a Node.js server with Express and Socket.io."
· Prompt 2: "Now, implement step 1: create the basic Express server in a file server.js."
2. Provide Examples (Few-Shot Learning): Show the AI the pattern you want.
```javascript
// Example 1: A function that adds two numbers
const add = (a, b) => a + b;
// Example 2: A function that multiplies two numbers
const multiply = (a, b) => a * b;
// Now, write a function that subtracts the second number from the first.
```
3. Use Code Comments to "Steer" the AI: As you type code, use comments to tell the AI what should come next. This is extremely effective in IDEs with inline completion.
```python
def calculate_total(cart):
subtotal = sum(item['price'] for item in cart)
# Now, apply a 10% tax if the subtotal is over $100, otherwise no tax.
# Then, apply a $5 shipping fee, but waive it if the final total is over $150.
# Finally, return the final total.
```
The AI will beautifully fill in the logic based on your comment.
By following this guide, you shift from hoping the AI understands you to knowing you've given it the best possible chance to succeed. Happy prompting
STEERING AI Coding Assistant
Comments