Prompt Engineering cho Code
1. Prompt Engineering là gì?
Prompt Engineering là kỹ năng viết instructions (prompts) để AI hiểu chính xác bạn muốn gì và sinh ra output tốt nhất.
Trong Vibe Coding, prompts của bạn là:
- Comments trong code
- Docstrings
- Function/variable names
- Chat messages trong Copilot Chat
2. Anatomy of a Good Prompt
Framework: CLEAR
CLEAR Prompt Framework
CLEAR
C - Context
L - Language/Library
E - Examples
A - Action
R - Requirements
Example áp dụng CLEAR
Python
1# Context: E-commerce checkout system2# Language: Python with Flask3# Action: Create function to calculate total price4# Requirements:5# - Apply discount code if valid6# - Add shipping fee based on location7# - Handle tax calculation (10%)8# Example:9# Input: items=[{"price": 100, "qty": 2}], discount="SAVE10", location="VN"10# Output: {"subtotal": 200, "discount": 20, "shipping": 30, "tax": 21, "total": 231}1112def calculate_checkout_total(items, discount_code=None, location="US"):13 # Copilot sẽ implement chính xác theo requirements!3. Comment Patterns hiệu quả
3.1 Task-Based Comments
Python
1# TODO: Implement binary search algorithm2# TODO: Add error handling for edge cases3# TODO: Optimize for large datasets45# FIXME: This function is too slow for large inputs6# FIXME: Memory leak when processing big files78# HACK: Temporary workaround for API rate limit3.2 Step-by-Step Comments
Python
1# Step 1: Read the CSV file2# Step 2: Clean the data (remove nulls, fix types)3# Step 3: Calculate summary statistics4# Step 4: Generate visualization5# Step 5: Export results to Excel67def analyze_sales_data(filepath):8 # Step 1: Read the CSV file9 df = pd.read_csv(filepath)10 11 # Step 2: Clean the data12 # Copilot continues...3.3 Input-Output Comments
Python
1# Input: List of student scores [{"name": str, "score": int}]2# Output: Dictionary with statistics {"avg": float, "max": int, "min": int, "passed": int}3# Note: Pass threshold is 5045def calculate_class_statistics(students):6 pass3.4 Constraint Comments
Python
1# Constraints:2# - Time complexity must be O(n log n) or better3# - Space complexity must be O(1)4# - Must handle negative numbers5# - Must not modify the original array67def sort_array_efficiently(arr):8 pass4. Copilot Chat Prompts
4.1 Slash Commands
| Command | Usage |
|---|---|
/explain | Giải thích code đang select |
/fix | Fix bugs trong code |
/tests | Generate unit tests |
/doc | Generate documentation |
/simplify | Simplify code |
/clear | Clear chat history |
4.2 Chat Prompt Templates
Explain Code:
Text
1/explain this function step by step, including time complexityDebug:
Text
1I'm getting this error: [paste error]2The code is: [paste code]3What's wrong and how to fix it?Refactor:
Text
1Refactor this code to:2- Use list comprehension instead of loops3- Add type hints4- Follow PEP 8 style guideGenerate:
Text
1Create a Python class for User with:2- Properties: name, email, created_at3- Methods: validate_email(), to_dict(), __str__()4- Use dataclass decorator5. Context Techniques
5.1 File Context
Copilot đọc file hiện tại và các file đang mở. Để tăng context:
Python
1# File: models/user.py2# Related files: models/base.py, utils/validators.py3# Database: PostgreSQL with SQLAlchemy45from .base import BaseModel6from utils.validators import validate_email78class User(BaseModel):9 # Copilot hiểu architecture từ context5.2 Project Context với @workspace
Trong Copilot Chat, dùng @workspace để reference toàn bộ project:
Text
1@workspace How is authentication implemented in this project?2@workspace Find all API endpoints that require admin access3@workspace What database models exist?5.3 Reference Other Files
Python
1# See also: utils/helpers.py for helper functions2# Based on: docs/api-spec.md34# Similar to: services/payment_service.py6. Anti-Patterns (Tránh làm)
❌ Vague Prompts
Python
1# Bad: Too vague2# Process the data3def process(data):4 pass56# Good: Specific7# Parse JSON data, extract user info, validate email format8def process_user_json(json_data):9 pass❌ Conflicting Instructions
Python
1# Bad: Contradictory2# Sort ascending, then reverse to descending3# Return first element which is largest45# Good: Clear single goal6# Return the largest element from the list❌ Too Complex in One Prompt
Python
1# Bad: Too much at once2# Build a complete REST API with user auth, CRUD for posts, 3# comments, likes, real-time notifications, admin dashboard...45# Good: Break down6# Step 1: Create Flask app skeleton7# Step 2: Add User model with basic fields8# Step 3: Implement register endpoint7. Language-Specific Tips
Python
Python
1# Use type hints - Copilot loves them!2def merge_dicts(dict1: dict, dict2: dict) -> dict:3 pass45# Mention specific libraries6# Using pandas DataFrame operations7# Using requests library for API callsJavaScript/TypeScript
TypeScript
1// TypeScript interfaces help a lot2interface User {3 id: number;4 name: string;5 email: string;6}78// Mention frameworks9// React functional component with useState and useEffect10// Express.js middleware for authenticationSQL
SQL
1-- Table schema: users(id, name, email, created_at)2-- Table schema: orders(id, user_id, amount, status, created_at)34-- Query: Get top 10 users by total order amount5-- Include: user name, email, total amount, order count6-- Filter: Only completed orders from last 30 days8. Advanced: Multi-turn Prompting
Đôi khi bạn cần "guide" Copilot qua nhiều bước:
Turn 1: Structure
Python
1# Web scraper for news articles2# Structure:3# - NewsArticle dataclass4# - Scraper class with methods5# - Main function67@dataclass8class NewsArticle:9 # Copilot generates fieldsTurn 2: Refine
Python
1# Add these fields: title, url, author, published_date, content2@dataclass3class NewsArticle:4 # Now Copilot has specific fieldsTurn 3: Add Logic
Python
1class NewsScraper:2 # Methods needed:3 # - __init__(self, base_url)4 # - fetch_page(self, url) -> BeautifulSoup5 # - parse_article(self, soup) -> NewsArticle6 # - scrape_all(self, max_pages=10) -> List[NewsArticle]9. Hands-on Exercise
Challenge: API Client với Prompt Engineering
Sử dụng các kỹ thuật đã học, viết prompts để Copilot generate một API client:
Python
1"""2Weather API Client34This module provides a client for OpenWeatherMap API.56Features:7- Get current weather by city name8- Get 5-day forecast9- Get weather by coordinates10- Cache results for 10 minutes to avoid rate limiting11- Handle API errors gracefully1213Dependencies: requests, cachetools1415API Reference: https://openweathermap.org/api1617Example Usage:18 client = WeatherClient(api_key="your_key")19 current = client.get_current("Hanoi")20 print(f"Temperature: {current.temperature}°C")21 22 forecast = client.get_forecast("Ho Chi Minh City", days=5)23 for day in forecast:24 print(f"{day.date}: {day.high}°C / {day.low}°C")25"""2627from dataclasses import dataclass28from typing import List, Optional29from datetime import datetime30import requests31from cachetools import TTLCache3233# TODO: Let Copilot implement based on the documentation above3435@dataclass36class Weather:37 # Let Copilot suggest fields based on context38 pass3940@dataclass 41class Forecast:42 # Let Copilot suggest fields43 pass4445class WeatherClient:46 # Let Copilot implement methods47 passEvaluation Criteria
Sau khi Copilot generate, check:
- Có đủ methods như mô tả không?
- Có caching không?
- Có error handling không?
- Code có clean và readable không?
- Types có correct không?
Tiếp theo
Bài tiếp theo chúng ta sẽ deep dive vào Copilot Chat - cách sử dụng chat interface để explain, debug, và refactor code!
