Chuyển đến nội dung chính

Bài 8: Nghệ thuật viết Prompt cho Code — Từ mơ hồ đến chính xác

Anatomy of a good code prompt: context, constraints, examples. Prompting patterns: zero-shot, few-shot, chain-of-thought cho code. Cách mô tả requirements rõ ràng. Iterative prompting. Common mistakes và cách khắc phục.

💻 Lập trình — Bài 8 Bài 8: Nghệ thuật viết Prompt cho Code — Từ mơ hồ đến chính xác

Vibe Coding với GitHub Copilot: Từ Cơ bản đến Nâng cao

Phần 3: Prompt Engineering cho Code

xdev.asia

1. Tại sao Prompt Engineering quan trọng cho Vibe Coding?

Trong Vibe Coding, prompt là code của bạn. Chất lượng output phụ thuộc trực tiếp vào chất lượng prompt. Một prompt tốt có thể tiết kiệm hàng giờ iterate, trong khi prompt tồi dẫn đến code sai hoàn toàn.

❌ Prompt tồi:  "Make a login page"
✅ Prompt tốt:  "Create a login page with email/password fields using React Hook Form,
                 Zod validation, error messages below each field, submit button
                 disabled until valid, loading spinner during API call,
                 redirect to /dashboard on success. Use our existing AuthContext
                 and api/auth endpoint. Follow the design system in styles/theme.ts"

2. Anatomy of a Good Code Prompt

Một prompt code hiệu quả có 5 thành phần:

┌─────────────────────────────────────────────────┐
│           PROMPT STRUCTURE                       │
├─────────────────────────────────────────────────┤
│                                                  │
│  1. CONTEXT     → Bối cảnh (tech stack, codebase)│
│  2. TASK        → Yêu cầu cụ thể                │
│  3. CONSTRAINTS → Ràng buộc (patterns, limits)   │
│  4. EXAMPLES    → Ví dụ input/output mong muốn  │
│  5. OUTPUT FORMAT → Định dạng kết quả           │
│                                                  │
└─────────────────────────────────────────────────┘

Ví dụ áp dụng:

// CONTEXT
We have a Next.js 15 app with App Router, TypeScript, Prisma ORM,
and PostgreSQL. Authentication uses NextAuth v5 with JWT strategy.

// TASK Create an API route handler for creating blog posts.

// CONSTRAINTS

  • Use Zod for request body validation
  • Return proper HTTP status codes (201 created, 400 validation error, 401 unauthorized)
  • Only authenticated users with "author" role can create posts
  • Slug should be auto-generated from title (URL-safe, Vietnamese diacritics removed)
  • Include created_at timestamp

// EXAMPLES Request body: { "title": "Hướng dẫn Docker", "content": "Nội dung bài viết...", "tags": ["docker", "devops"] }

Expected response (201): { "id": "clx...", "title": "Hướng dẫn Docker", "slug": "huong-dan-docker", "content": "Nội dung bài viết...", "tags": ["docker", "devops"], "author_id": "user123", "created_at": "2026-03-31T12:00:00Z" }

// OUTPUT FORMAT Create the file at src/app/api/posts/route.ts following our existing API patterns.

3. Prompting Patterns cho Code

3.1. Zero-shot — Không ví dụ

// Đơn giản, nhanh. Phù hợp khi task rõ ràng:
Create a TypeScript utility function to deep merge two objects,
handling arrays by concatenation and nested objects recursively.

3.2. Few-shot — Có ví dụ

// Cung cấp examples để AI hiểu pattern mong muốn:
Create a validation function following this pattern:

// Example 1: validateEmail("[email protected]") → { valid: true } validateEmail("invalid") → { valid: false, error: "Invalid email format" }

// Example 2: validatePhone("+84912345678") → { valid: true } validatePhone("abc") → { valid: false, error: "Invalid phone number" }

// Now create: validateUsername(username) with rules:

  • 3-20 characters
  • Only alphanumeric and underscore
  • Cannot start with number

3.3. Chain-of-Thought — Suy luận từng bước

// Yêu cầu AI "think step by step":
Design a rate limiter middleware for Express.js.
Think step by step:
1. First, decide on the algorithm (token bucket vs sliding window)
2. Then, choose the storage (in-memory vs Redis)
3. Implement the middleware with configurable options
4. Add proper error responses and headers
5. Write unit tests for edge cases

3.4. Role-based — Đặt vai trò cho AI

// Cho AI một persona:
Act as a senior security engineer reviewing this authentication code.
Identify all security vulnerabilities and suggest fixes with code examples.
Focus on: injection attacks, token handling, password storage, rate limiting.

4. Iterative Prompting — Cải thiện dần

Vibe Coding hiệu quả là một cuộc hội thoại, không phải một prompt duy nhất:

// Round 1: Tạo cơ bản
Create a search component for our blog with debounced input.

// Round 2: Cải thiện
Good, but add these improvements:
- Show loading skeleton while fetching
- Handle empty results with a friendly message
- Add keyboard navigation (arrow keys to select, Enter to open)

// Round 3: Edge cases
Now handle these edge cases:
- Search query less than 3 characters → show "Type at least 3 characters"
- API error → show retry button
- Very long results → add pagination with "Load more"

// Round 4: Polish
Finally, add proper ARIA attributes for accessibility
and transition animations for smooth UX.

5. Common Mistakes và cách khắc phục

Sai lầm Ví dụ Khắc phục
Quá mơ hồ "Make a dashboard" Specify metrics, charts, data source, layout
Quá dài 500+ words trong 1 prompt Chia thành nhiều iterations
Không có context "Add authentication" Specify framework, strategy, existing code
Contradictory "Use REST but real-time" Rõ ràng: REST + WebSocket cho real-time
No constraints "Create an API" Specify error handling, auth, validation
Tiếng Việt lẫn English "Tạo function để check hợp lệ" Nhất quán: full English hoặc full Vietnamese

6. Prompt Templates sẵn dùng

Template: New Feature

Create [FEATURE_NAME] for our [FRAMEWORK] app.

Context:

  • Tech stack: [STACK]
  • Current architecture: [PATTERN]
  • Related files: [FILE_PATHS]

Requirements:

  1. [REQUIREMENT_1]
  2. [REQUIREMENT_2]
  3. [REQUIREMENT_3]

Constraints:

  • Follow [PATTERN_NAME] pattern
  • Use [LIBRARY] for [PURPOSE]
  • Handle errors with [STRATEGY]
  • Include [TEST_TYPE] tests

Template: Bug Fix

Fix this bug: [BUG_DESCRIPTION]

Error message: [ERROR_MESSAGE]

Steps to reproduce:

  1. [STEP_1]
  2. [STEP_2]

Expected behavior: [EXPECTED] Actual behavior: [ACTUAL]

Relevant files: [FILE_PATHS]

Template: Refactoring

Refactor [CODE_DESCRIPTION] to improve [QUALITY_ATTRIBUTE].

Current issues:

  • [ISSUE_1]
  • [ISSUE_2]

Target state:

  • [DESIRED_STATE_1]
  • [DESIRED_STATE_2]

Constraints:

  • Don't change the public API
  • Maintain backward compatibility
  • Keep test coverage above [X]%

7. Tiếng Anh vs Tiếng Việt trong Prompt

AI models (GPT, Claude) được train chủ yếu bằng tiếng Anh, nên:

  • Prompt bằng tiếng Anh thường cho kết quả tốt hơn cho code
  • Prompt tiếng Việt OK cho: giải thích, documentation, comments
  • Mixed (Việt + code terms English) cũng hoạt động tốt với Copilot
// OK - Mixed language:
Tạo một middleware xử lý rate limiting cho Express.js,
sử dụng sliding window algorithm với Redis.

// Better - Full English cho complex code tasks:
Create a rate limiting middleware for Express.js using
sliding window algorithm with Redis backend.

8. Tổng kết

Pattern Khi nào dùng
Zero-shot Task đơn giản, rõ ràng
Few-shot Cần output theo pattern cụ thể
Chain-of-Thought Logic phức tạp, design decisions
Role-based Security review, code review, specific expertise
Iterative Mọi task (nên dùng luôn)

Bài tiếp theo sẽ đi sâu vào Context Management — cách cung cấp đúng ngữ cảnh để AI hiểu codebase của bạn.