Lý thuyết
30 phút
Bài 4/12

Prompt Engineering cho Code

Nghệ thuật viết comments và prompts để Copilot sinh code chính xác theo ý bạn

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 system
2# Language: Python with Flask
3# Action: Create function to calculate total price
4# Requirements:
5# - Apply discount code if valid
6# - Add shipping fee based on location
7# - 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}
11
12def 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 algorithm
2# TODO: Add error handling for edge cases
3# TODO: Optimize for large datasets
4
5# FIXME: This function is too slow for large inputs
6# FIXME: Memory leak when processing big files
7
8# HACK: Temporary workaround for API rate limit

3.2 Step-by-Step Comments

Python
1# Step 1: Read the CSV file
2# Step 2: Clean the data (remove nulls, fix types)
3# Step 3: Calculate summary statistics
4# Step 4: Generate visualization
5# Step 5: Export results to Excel
6
7def analyze_sales_data(filepath):
8 # Step 1: Read the CSV file
9 df = pd.read_csv(filepath)
10
11 # Step 2: Clean the data
12 # 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 50
4
5def calculate_class_statistics(students):
6 pass

3.4 Constraint Comments

Python
1# Constraints:
2# - Time complexity must be O(n log n) or better
3# - Space complexity must be O(1)
4# - Must handle negative numbers
5# - Must not modify the original array
6
7def sort_array_efficiently(arr):
8 pass

4. Copilot Chat Prompts

4.1 Slash Commands

CommandUsage
/explainGiải thích code đang select
/fixFix bugs trong code
/testsGenerate unit tests
/docGenerate documentation
/simplifySimplify code
/clearClear chat history

4.2 Chat Prompt Templates

Explain Code:

Text
1/explain this function step by step, including time complexity

Debug:

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 loops
3- Add type hints
4- Follow PEP 8 style guide

Generate:

Text
1Create a Python class for User with:
2- Properties: name, email, created_at
3- Methods: validate_email(), to_dict(), __str__()
4- Use dataclass decorator

5. 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.py
2# Related files: models/base.py, utils/validators.py
3# Database: PostgreSQL with SQLAlchemy
4
5from .base import BaseModel
6from utils.validators import validate_email
7
8class User(BaseModel):
9 # Copilot hiểu architecture từ context

5.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 access
3@workspace What database models exist?

5.3 Reference Other Files

Python
1# See also: utils/helpers.py for helper functions
2# Based on: docs/api-spec.md
3
4# Similar to: services/payment_service.py

6. Anti-Patterns (Tránh làm)

❌ Vague Prompts

Python
1# Bad: Too vague
2# Process the data
3def process(data):
4 pass
5
6# Good: Specific
7# Parse JSON data, extract user info, validate email format
8def process_user_json(json_data):
9 pass

❌ Conflicting Instructions

Python
1# Bad: Contradictory
2# Sort ascending, then reverse to descending
3# Return first element which is largest
4
5# Good: Clear single goal
6# Return the largest element from the list

❌ Too Complex in One Prompt

Python
1# Bad: Too much at once
2# Build a complete REST API with user auth, CRUD for posts,
3# comments, likes, real-time notifications, admin dashboard...
4
5# Good: Break down
6# Step 1: Create Flask app skeleton
7# Step 2: Add User model with basic fields
8# Step 3: Implement register endpoint

7. Language-Specific Tips

Python

Python
1# Use type hints - Copilot loves them!
2def merge_dicts(dict1: dict, dict2: dict) -> dict:
3 pass
4
5# Mention specific libraries
6# Using pandas DataFrame operations
7# Using requests library for API calls

JavaScript/TypeScript

TypeScript
1// TypeScript interfaces help a lot
2interface User {
3 id: number;
4 name: string;
5 email: string;
6}
7
8// Mention frameworks
9// React functional component with useState and useEffect
10// Express.js middleware for authentication

SQL

SQL
1-- Table schema: users(id, name, email, created_at)
2-- Table schema: orders(id, user_id, amount, status, created_at)
3
4-- Query: Get top 10 users by total order amount
5-- Include: user name, email, total amount, order count
6-- Filter: Only completed orders from last 30 days

8. 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 articles
2# Structure:
3# - NewsArticle dataclass
4# - Scraper class with methods
5# - Main function
6
7@dataclass
8class NewsArticle:
9 # Copilot generates fields

Turn 2: Refine

Python
1# Add these fields: title, url, author, published_date, content
2@dataclass
3class NewsArticle:
4 # Now Copilot has specific fields

Turn 3: Add Logic

Python
1class NewsScraper:
2 # Methods needed:
3 # - __init__(self, base_url)
4 # - fetch_page(self, url) -> BeautifulSoup
5 # - parse_article(self, soup) -> NewsArticle
6 # - 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 Client
3
4This module provides a client for OpenWeatherMap API.
5
6Features:
7- Get current weather by city name
8- Get 5-day forecast
9- Get weather by coordinates
10- Cache results for 10 minutes to avoid rate limiting
11- Handle API errors gracefully
12
13Dependencies: requests, cachetools
14
15API Reference: https://openweathermap.org/api
16
17Example 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"""
26
27from dataclasses import dataclass
28from typing import List, Optional
29from datetime import datetime
30import requests
31from cachetools import TTLCache
32
33# TODO: Let Copilot implement based on the documentation above
34
35@dataclass
36class Weather:
37 # Let Copilot suggest fields based on context
38 pass
39
40@dataclass
41class Forecast:
42 # Let Copilot suggest fields
43 pass
44
45class WeatherClient:
46 # Let Copilot implement methods
47 pass

Evaluation 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!