Buổi 02: Advanced Prompting — Kỹ Thuật Prompt Cho Developer 🧠
Thành quả: Viết được Chain-of-Thought prompt tạo full API endpoint (route + controller + test)
🎯 Mục Tiêu
- Master 7 kỹ thuật prompting cho developer
- Viết chain prompts tạo code production-quality
- Hiểm context window, token limits, và cách quản lý
- Sử dụng few-shot prompting cho consistent code style
- Debug prompt khi AI output không như mong đợi
📖 Phần 1: Beyond PTCFC — Developer Prompting
7 Kỹ Thuật Prompting Nâng Cao
| # | Technique | Use Case | Effectiveness |
|---|---|---|---|
| 1 | Zero-Shot | Câu hỏi đơn giản | ⭐⭐ |
| 2 | Few-Shot | Cần consistent format/style | ⭐⭐⭐⭐ |
| 3 | Chain-of-Thought (CoT) | Logic phức tạp, algorithms | ⭐⭐⭐⭐⭐ |
| 4 | Role-Play | Chuyên gia specific domain | ⭐⭐⭐⭐ |
| 5 | Chain Prompting | Multi-step code generation | ⭐⭐⭐⭐⭐ |
| 6 | Constraint Prompting | Code phải tuân theo chuẩn | ⭐⭐⭐⭐ |
| 7 | Iterative Refinement | Improve output step-by-step | ⭐⭐⭐⭐⭐ |
1. Zero-Shot (Baseline)
"Viết function sort array"
→ AI trả về code chung chung, có thể không match stack của bạn2. Few-Shot — Cho Ví Dụ Mẫu
markdown
Viết Express.js controller theo pattern này:
Ví dụ 1 (GET /users):
```javascript
const getUsers = asyncHandler(async (req, res) => {
const users = await User.find().select('-password');
res.json({ success: true, data: users, count: users.length });
});Ví dụ 2 (GET /users/:id):
javascript
const getUserById = asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id).select('-password');
if (!user) throw new AppError('User not found', 404);
res.json({ success: true, data: user });
});Bây giờ viết controller cho: POST /products (name, price, category required) → AI sẽ follow ĐÚNG pattern: asyncHandler, error handling, response format
### 3. Chain-of-Thought (CoT)
```markdown
Thiết kế authentication flow cho REST API.
Hãy suy nghĩ từng bước:
Bước 1: Liệt kê các endpoint cần thiết (register, login, refresh, logout)
Bước 2: Xác định data flow cho mỗi endpoint
Bước 3: Thiết kế JWT strategy (access token + refresh token)
Bước 4: Xác định middleware cần thiết
Bước 5: Viết code cho từng phần
Giải thích reasoning ở mỗi bước trước khi viết code.4. Role-Play Expert
markdown
Bạn là Senior Backend Engineer với 10 năm kinh nghiệm về Node.js,
đã xây dựng nhiều hệ thống xử lý 10,000+ requests/second.
Code architecture standards:
- Clean Architecture (controller → service → repository)
- Error handling: centralized error handler
- Validation: Joi/Zod schema validation
- Testing: Jest + Supertest
- Logging: structured JSON logs
Nhiệm vụ: Review và refactor file auth.controller.js này:
[paste code]5. Chain Prompting (Multi-Step)
Prompt 1: "Thiết kế database schema cho e-commerce (users, products, orders, reviews)"
→ Output: Schema design
Prompt 2: "Dựa vào schema trên, viết Prisma models cho mỗi table"
→ Output: Prisma schema
Prompt 3: "Dựa vào models trên, viết CRUD API routes cho Products"
→ Output: API routes
Prompt 4: "Viết unit tests cho mỗi endpoint Products đã tạo"
→ Output: Test files
Mỗi prompt BUILD ON output của prompt trước!6. Constraint Prompting
markdown
Viết React component theo CONSTRAINTS sau:
MUST:
- TypeScript strict mode
- Functional component + hooks only
- Error boundary handling
- Loading state management
- Memoization cho expensive renders
MUST NOT:
- No `any` type
- No inline styles
- No `useEffect` for data fetching (use React Query)
- No prop drilling > 2 levels (use Context or Zustand)
Component: ProductList hiển thị danh sách sản phẩm từ API /products7. Iterative Refinement
Round 1: "Viết login form React"
→ Output: Basic form
Round 2: "Thêm validation: email format, password min 8 chars, show/hide password"
→ Output: Form + validation
Round 3: "Thêm loading state, error display, rate limiting (max 5 attempts)"
→ Output: Production-ready form
Round 4: "Viết unit tests cho form này: happy path + validation errors + rate limit"
→ Output: Full test suite📖 Phần 2: Context Window Management
Problem: Token Limits
Model Context Window ≈ Characters
Gemini 2.5 Pro 1M tokens ~4M chars (400 files!)
Gemini 2.5 Flash 1M tokens ~4M chars
GPT-4o 128K tokens ~500K chars
Claude 3.5 200K tokens ~800K charsStrategies cho Large Codebases
| Strategy | Khi nào | Cách làm |
|---|---|---|
| Skeleton Index | Onboard project | cm-codeintell → compressed overview |
| Selective Context | Sửa 1-2 files | Chỉ paste relevant files, không cả project |
| Chunking | File > 500 lines | Chia thành sections, prompt từng phần |
| Reference Anchoring | Multi-file change | Paste interface/types trước, implementation sau |
| Progressive Detail | Explore → Deep dive | Overview prompt → Detail prompt cho specific area |
Context Template
markdown
## Project Context
- Stack: [Node.js + Express + Prisma + PostgreSQL]
- Architecture: [Clean Architecture with layers]
- This file: [src/services/order.service.ts]
- Related files: [models/order.ts, routes/order.routes.ts]
## Current Task
[Specific task description]
## Relevant Code
[Only the code that matters for this task]
## Constraints
[Code style, patterns to follow, things to avoid]📖 Phần 3: Prompt Debugging
Khi AI Output Sai
| Symptom | Root Cause | Fix |
|---|---|---|
| Code sai logic | Prompt thiếu context | Thêm CoT: "suy nghĩ từng bước" |
| Sai code style | Không có ví dụ mẫu | Dùng Few-Shot |
| Hallucinate API | AI không biết version | Specify exact version + link docs |
| Import sai library | Không biết stack | Liệt kê dependencies trong prompt |
| Code quá phức tạp | Prompt quá rộng | Chia nhỏ bằng Chain Prompting |
| Thiếu error handling | Không yêu cầu | Thêm vào Constraints |
Prompt Debugging Checklist
✅ Context đủ chưa? (tech stack, architecture, related code)
✅ Task rõ ràng chưa? (specific, measurable)
✅ Constraints liệt kê chưa? (must/must not)
✅ Format output chỉ định chưa? (file structure, code style)
✅ Ví dụ mẫu có chưa? (few-shot nếu cần consistency)📖 Phần 4: Prompt Templates Cho Dev
Template 1: API Endpoint
markdown
[Role] Senior Node.js developer
[Task] Tạo REST endpoint: [METHOD] [PATH]
[Context]
- Stack: Express + TypeScript + Prisma + PostgreSQL
- Auth: JWT Bearer token
- Validation: Zod schemas
- Error: Centralized AppError class
[Format]
- File 1: route definition (routes/[resource].routes.ts)
- File 2: controller (controllers/[resource].controller.ts)
- File 3: service (services/[resource].service.ts)
- File 4: validation schema (schemas/[resource].schema.ts)
- File 5: unit test (tests/[resource].test.ts)
[Constraints]
- Follow existing patterns in codebase
- 100% TypeScript strict
- Test coverage cho happy path + error casesTemplate 2: React Component
markdown
[Role] Senior React developer
[Task] Tạo component: [ComponentName]
[Context]
- Stack: React 18 + TypeScript + TanStack Query + Zustand
- Design: Tailwind CSS + Shadcn/ui
- Props interface defined first
[Format] Single file component with:
1. TypeScript interface cho props
2. Component implementation
3. Custom hook nếu cần
4. Storybook story
5. Unit test (Vitest + Testing Library)
[Constraints]
- No `any` types
- Memoize nếu re-render expensive
- Accessible (ARIA labels, keyboard nav)Template 3: Database Schema
markdown
[Role] Database architect
[Task] Thiết kế schema cho: [Feature]
[Context]
- Database: PostgreSQL
- ORM: Prisma
- Existing tables: [list]
[Format]
1. ER Diagram (mermaid)
2. Prisma model definitions
3. Migration SQL
4. Seed data
[Constraints]
- Proper indexing
- Foreign key constraints
- Soft delete (deletedAt) pattern
- Audit fields (createdAt, updatedAt, createdBy)🧪 Lab: Chain Prompt Exercise
Bài tập: Tạo Blog API (4 chain prompts)
Prompt 1: "Thiết kế DB schema cho blog system:
- Users (name, email, password, role)
- Posts (title, content, slug, status (draft/published), author)
- Comments (content, author, post)
- Tags (name) with many-to-many to Posts"
Prompt 2: "Dựa vào schema, viết Prisma models + migration"
Prompt 3: "Tạo CRUD endpoints cho Posts:
- GET /posts (paginated, filter by status/tag)
- GET /posts/:slug
- POST /posts (auth required)
- PUT /posts/:id (author only)
- DELETE /posts/:id (author/admin)"
Prompt 4: "Viết unit tests cho mỗi endpoint, include:
- Happy path
- Auth errors (no token, wrong role)
- Validation errors (missing fields)
- Not found errors"🎓 Tóm Tắt
| Technique | Best For |
|---|---|
| Few-Shot | Consistent code style |
| CoT | Complex logic, algorithms |
| Chain Prompting | Multi-file feature generation |
| Constraint | Enforce code standards |
| Iterative | Progressive improvement |
⏭️ Buổi tiếp theo
Buổi 03: Dev Environment PRO — Terminal, Git, và Workflow ⚡