Skip to content

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

  1. Master 7 kỹ thuật prompting cho developer
  2. Viết chain prompts tạo code production-quality
  3. Hiểm context window, token limits, và cách quản lý
  4. Sử dụng few-shot prompting cho consistent code style
  5. 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

#TechniqueUse CaseEffectiveness
1Zero-ShotCâu hỏi đơn giản⭐⭐
2Few-ShotCần consistent format/style⭐⭐⭐⭐
3Chain-of-Thought (CoT)Logic phức tạp, algorithms⭐⭐⭐⭐⭐
4Role-PlayChuyên gia specific domain⭐⭐⭐⭐
5Chain PromptingMulti-step code generation⭐⭐⭐⭐⭐
6Constraint PromptingCode phải tuân theo chuẩn⭐⭐⭐⭐
7Iterative RefinementImprove 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ạn

2. 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 /products

7. 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 chars

Strategies cho Large Codebases

StrategyKhi nàoCách làm
Skeleton IndexOnboard projectcm-codeintell → compressed overview
Selective ContextSửa 1-2 filesChỉ paste relevant files, không cả project
ChunkingFile > 500 linesChia thành sections, prompt từng phần
Reference AnchoringMulti-file changePaste interface/types trước, implementation sau
Progressive DetailExplore → Deep diveOverview 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

SymptomRoot CauseFix
Code sai logicPrompt thiếu contextThêm CoT: "suy nghĩ từng bước"
Sai code styleKhông có ví dụ mẫuDùng Few-Shot
Hallucinate APIAI không biết versionSpecify exact version + link docs
Import sai libraryKhông biết stackLiệt kê dependencies trong prompt
Code quá phức tạpPrompt quá rộngChia nhỏ bằng Chain Prompting
Thiếu error handlingKhông yêu cầuThê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 cases

Template 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

TechniqueBest For
Few-ShotConsistent code style
CoTComplex logic, algorithms
Chain PromptingMulti-file feature generation
ConstraintEnforce code standards
IterativeProgressive improvement

⏭️ Buổi tiếp theo

Buổi 03: Dev Environment PRO — Terminal, Git, và Workflow

Powered by CodyMaster × VitePress