AI Prompt Engineering: Hướng Dẫn Đầy Đủ Để Có Kết Quả Tốt Hơn Từ ChatGPT, Claude và GitHub Copilot
Prompt engineering là nghệ thuật và khoa học thiết kế các hướng dẫn khai thác khả năng tốt nhất từ mô hình AI. Mặc dù các công cụ như ChatGPT, Claude và GitHub Copilot vô cùng mạnh mẽ, nhưng đầu ra của chúng chỉ tốt bằng prompt bạn cung cấp. Một prompt được thiết kế tốt có thể tạo ra mã sạch, có thể production-ready, phân tích sâu sắc và giải pháp sáng tạo. Một prompt yếu tạo ra kết quả chung chung, sai sót hoặc không liên quan. Hướng dẫn này bao gồm các nguyên lý cốt lõi, kỹ thuật nâng cao, chiến lược theo công cụ cụ thể và phương pháp kiểm tra có hệ thống để giúp bạn thành thạo prompt engineering, bất kể bạn đang sử dụng công cụ AI nào.
Prompt Engineering Là Gì?
Prompt engineering đã phát triển từ một kỹ thuật thích hợp thành một kỹ năng chuyên nghiệp được công nhận. Khi các mô hình AI trở nên mạnh mẽ hơn, khả năng mở khóa thông qua prompt khéo léo cũng phát triển tương ứng. Các mô hình ban đầu cần hướng dẫn đơn giản, nhưng các mô hình hiện nay có thể tuân theo các ràng buộc phức tạp, lập luận qua nhiều bước và thích ứng với phong cách giao tiếp của bạn — tất cả phụ thuộc vào chất lượng prompt của bạn.
Thành thạo prompt engineering bắt đầu với việc hiểu các nguyên tắc cơ bản. Sáu nguyên lý cốt lõi này áp dụng phổ quát trên tất cả mô hình AI và trường hợp sử dụng.
Prompt mơ hồ tạo ra đầu ra mơ hồ. Prompt của bạn càng cụ thể, kết quả càng chính xác. Thay vì "viết một hàm để sắp xếp dữ liệu", hãy chỉ định: "viết một hàm Python sắp xếp danh sách từ điển theo khóa 'date' theo thứ tự giảm dần, xử lý giá trị None bằng cách đặt chúng ở cuối, và bao gồm type hint."
Nguyên Lý Cốt Lõi Của Prompt Engineering
Tính cụ thể cũng áp dụng cho những gì bạn không muốn. Nếu có những cách tiếp cận bạn muốn tránh, hãy nói rõ. Ví dụ: "giải thích khái niệm này mà không sử dụng biệt ngữ kỹ thuật" hoặc "viết mã này mà không sử dụng thư viện bên ngoài."
Sự Thăng Tiến Của Prompt Engineering
Mô hình AI hoạt động tốt nhất khi chúng hiểu bức tranh toàn cảnh. Cung cấp ngữ cảnh về codebase, hệ thống hoặc vấn đề của bạn trước khi đặt câu hỏi. Đối với câu hỏi lập trình, hãy đề cập đến stack công nghệ, phiên bản và quy ước của bạn. Đối với vấn đề kinh doanh, hãy giải thích ngành, đối tượng và ràng buộc của bạn.
Write a Python function that validates an email address using regex.
The function should return True for valid emails and False for invalid ones.Đối với tương tác dựa trên dự án, hãy cân nhắc tạo tệp ngữ cảnh mà AI đọc khi bắt đầu phiên. Claude Code sử dụng CLAUDE.md cho mục đích này, và Cursor sử dụng .cursorrules. Các tệp này cung cấp ngữ cảnh dự án liên tục mà không cần lặp lại trong mỗi prompt.
Tính Cụ Thể
Đối với các vấn đề phức tạp, hãy hướng dẫn AI suy nghĩ từng bước. Điều này thường được gọi là chain-of-thought prompting và cải thiện đáng kể chất lượng suy luận. Thay vì yêu cầu câu trả lời ngay lập tức, hãy yêu cầu AI chia nhỏ vấn đề, xem xét các cách tiếp cận khác nhau và sau đó đưa ra giải pháp.
Convert these database column names to camelCase JavaScript variable names:
user_first_name -> userFirstName
created_at_timestamp -> createdAtTimestamp
is_email_verified -> isEmailVerified
total_order_count ->
Now convert: product_category_idKỹ thuật này đặc biệt mạnh mẽ cho gỡ lỗi, quyết định kiến trúc và giải quyết vấn đề toán học. Nó buộc AI phải thể hiện quá trình suy luận, giúp bạn dễ dàng phát hiện lỗi logic và hiểu cách AI đi đến kết luận.
Ngữ Cảnh
Ràng buộc định hình không gian giải pháp. Bằng cách chỉ định giới hạn, bạn ngăn AI tạo ra các giải pháp không thực tế hoặc không mong muốn. Ràng buộc có thể là kỹ thuật (giới hạn ngôn ngữ, thư viện hoặc API), phong cách (tuân theo mẫu hoặc quy ước cụ thể) hoặc thực tế (giới hạn hiệu suất, yêu cầu khả năng truy cập).
Analyze this React component for performance issues. Think step by step:
1. First, identify all state variables and their update patterns
2. Then, check for unnecessary re-renders
3. Next, look for missing memoization opportunities
4. Finally, suggest specific optimizations with code examples
Here's the component:
[component code]Ví dụ, thay vì "viết API endpoint", hãy thử: "viết một API endpoint RESTful bằng Express.js xử lý tải lên tệp lên đến 10MB, xác thực loại MIME và lưu trữ tệp trong Amazon S3. Sử dụng async/await, xử lý lỗi với try/catch, và trả về mã trạng thái HTTP phù hợp."
Tư Duy Từng Bước
Cho AI biết chính xác định dạng đầu ra bạn muốn. Điều này có thể là một ngôn ngữ lập trình cụ thể, cấu trúc JSON, schema bảng, hoặc thậm chí là một phong cách viết cụ thể. Nếu bạn cần JSON, hãy chỉ định schema. Nếu bạn cần markdown, hãy chỉ định cấu trúc tiêu đề. Nếu bạn cần mã, hãy chỉ định ngôn ngữ và quy ước.
Act as a senior security engineer with 15 years of experience in web application security. Review this authentication implementation and identify any vulnerabilities, ranking them by severity. For each vulnerability, explain the attack vector and provide a secure code fix.Đối với đầu ra có cấu trúc, hãy cung cấp một ví dụ về định dạng mong muốn. Điều này giảm sự mơ hồ và đảm bảo AI tạo ra đầu ra trong cấu trúc chính xác bạn cần.
Ràng Buộc
Chỉ định vai hoặc persona cho AI cải thiện đáng kể chất lượng đầu ra. Khi bạn nói "bạn là một kỹ sư bảo mật cấp cao đang xem xét mã này để tìm lỗ hổng", AI kích hoạt kiến thức và mẫu suy luận liên quan đến lĩnh vực đó. Phân vai hoạt động vì mô hình ngôn ngữ liên kết vai trò với các mẫu kiến thức, phong cách giao tiếp và cách tiếp cận giải quyết vấn đề cụ thể.
Các phân vai hiệu quả bao gồm: senior software engineer, technical writer, code reviewer, database architect, accessibility specialist, performance engineer, security auditor, DevOps engineer, UI/UX designer, product manager, và data scientist. Phân vai càng cụ thể, đầu ra càng phù hợp.
# System prompt example
You are a TypeScript expert working on a Next.js 14 project using:
- App Router (not Pages Router)
- Server Components by default
- Prisma for database access
- Tailwind CSS for styling
- Zod for validation
Always use strict TypeScript. Prefer server actions over API routes.
Never use 'any' type. Use 'unknown' and narrow with type guards.
# User prompt example
Add a user profile page that shows the current user's name, email,
avatar, and last 10 activity records. Include loading states and
error handling.Kỹ Thuật Prompt Nâng Cao
Ngoài các nguyên lý cốt lõi, các kỹ thuật nâng cao có thể mở khóa khả năng mạnh mẽ hơn nữa từ mô hình AI.
| Biến Thể | Tính Cụ Thể | Ngữ Cảnh |
|---|---|---|
| A (cơ bản) | Thấp | Tối thiểu |
| Không có | Không chỉ định | Chung chung, cần sửa đổi |
| B (cải thiện) | Trung bình | Trung bình |
| Chung chung | Chỉ định | Tốt hơn, cần ít sửa đổi hơn |
| C (nâng cao) | Cao | Toàn diện |
| Cụ thể | Ví dụ + schema | Xuất sắc, sẵn sàng production |
"Refactor using..." | Pattern-based refactoring | Applying design patterns |
"Find bugs in" | Debugging | Identifying hidden issues |
"Convert from X to Y" | Code translation | Language or framework migration |
"Document this" | Documentation generation | Creating inline docs and READMEs |
"Optimize for performance" | Optimization | Improving speed and efficiency |
"Add error handling" | Robustness | Making code production-ready |
Định Dạng Đầu Ra
Chain-of-thought prompting hướng dẫn AI giải thích quá trình suy luận từng bước trước khi đưa ra câu trả lời cuối cùng. Điều này cải thiện độ chính xác cho các nhiệm vụ suy luận phức tạp bằng cách buộc AI xử lý vấn đề một cách có hệ thống thay vì nhảy đến kết luận.
You are a senior backend engineer at a fintech company who specializes
in building secure, high-throughput payment processing systems.
You have deep expertise in PostgreSQL, Redis, and distributed systems.
You always consider edge cases, race conditions, and failure modes.
Design a payment processing API that handles:
- Credit card payments via Stripe
- Bank transfers via Plaid
- Retry logic with exponential backoff
- Idempotency keys to prevent duplicate chargesPhân Vai
Thêm các cụm từ như "hãy suy nghĩ từng bước", "giải thích quá trình suy luận của bạn" hoặc "chia nhỏ vấn đề này" vào prompt của bạn. Đối với các vấn đề đặc biệt phức tạp, hãy yêu cầu AI xem xét nhiều cách tiếp cận, đánh giá ưu nhược điểm của từng cách, sau đó chọn giải pháp tốt nhất.
Debug this SQL query that's causing a timeout. Think step by step:
1. First, analyze the query structure and joins
2. Identify potential performance bottlenecks
3. Check for missing indexes
4. Suggest an optimized version with EXPLAIN analysis
SELECT u.name, COUNT(o.id), SUM(o.amount)
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
LEFT JOIN order_items oi ON o.id = oi.order_id
WHERE o.created_at > '2026-01-01'
GROUP BY u.name
HAVING COUNT(o.id) > 10
ORDER BY SUM(o.amount) DESC;Chain-of-Thought Prompting
Few-shot prompting cung cấp cho AI các ví dụ về hành vi mong muốn trước khi yêu cầu nó thực hiện nhiệm vụ. Bằng cách hiển thị 2-5 ví dụ về đầu vào và đầu ra mong muốn, bạn thiết lập mẫu mà AI có thể tuân theo. Kỹ thuật này đặc biệt hiệu quả để thiết lập định dạng đầu ra, phong cách mã hóa hoặc mẫu suy luận.
I need to choose between WebSocket and Server-Sent Events for a
real-time notification system. Think aloud about the trade-offs,
considering: browser support, bidirectional communication needs,
server resource usage, and scalability. Then recommend one with
justification.Few-Shot Prompting
Ví dụ, khi muốn AI tạo commit message, trước tiên hiển thị 3-4 commit message theo phong cách ưa thích, sau đó yêu cầu nó tạo commit message cho thay đổi mới. AI sẽ bắt chước định dạng, giọng điệu và mức độ chi tiết.
Explain like I'm 5: What is a monad in functional programming,
and why do Haskell developers keep talking about them?
Use a real-world analogy, not code.Tree-of-Thought Prompting
Tree-of-thought prompting mở rộng chain-of-thought bằng cách khám phá nhiều đường suy luận song song. Thay vì theo một chuỗi suy luận duy nhất, AI tạo ra nhiều cách tiếp cận, đánh giá từng cách và chọn hoặc kết hợp những cách tốt nhất. Điều này đặc biệt có giá trị cho các vấn đề mở không có giải pháp rõ ràng duy nhất.
Review and critique this Express.js middleware. Focus on:
- Security vulnerabilities
- Error handling gaps
- Performance concerns
- Best practice violations
- Suggest improvements with code examples
[paste your middleware code]Prompt Templates
Để sử dụng tree-of-thought prompting, hãy yêu cầu AI: "đề xuất ba cách tiếp cận khác nhau để giải quyết vấn đề này, đánh giá ưu nhược điểm của từng cách, sau đó đề xuất cách tiếp cận tốt nhất kèm lý do."
Write tests for the UserService.register method using Jest.
Cover these scenarios:
- Happy path with valid input
- Duplicate email registration
- Invalid email format
- Password too short
- Missing required fields
- Database connection failure
- Concurrent registration attempts
Use describe/it blocks. Include setup and teardown.
Mock the database layer.Prompt Chaining
Prompt templates là các mẫu có thể tái sử dụng tiêu chuẩn hóa cách bạn tương tác với AI cho các nhiệm vụ lặp lại. Tạo template cho các hoạt động phổ biến như tạo API endpoint, viết unit test, thực hiện code review, viết tài liệu và tạo migration cơ sở dữ liệu. Template đảm bảo tính nhất quán, tiết kiệm thời gian và giúp dễ dàng onboarding thành viên mới trong nhóm.
Refactor this notification system using the Strategy pattern.
Currently, all notification types (email, SMS, push) are handled
in a single class with if-else chains. Create separate strategy
classes for each notification type, a context class that delegates
to the active strategy, and a factory for creating strategies.
[paste your current code]Retrieval-Augmented Generation (RAG)
Lưu trữ template của bạn trong thư mục dự án hoặc tệp cấu hình để tất cả thành viên trong nhóm có thể truy cập. Nhiều công cụ hỗ trợ template tích hợp, cho phép bạn định nghĩa prompt có thể tái sử dụng mà bạn có thể gọi bằng tên.
Find bugs in this async Node.js function. It's supposed to process
a batch of orders and update their status, but sometimes orders
get processed twice and the status updates are inconsistent under
high load.
[paste your function code]Prompt Engineering Cho ChatGPT
Prompt chaining chia nhiệm vụ phức tạp thành chuỗi prompt nhỏ hơn, tập trung, trong đó đầu ra của prompt này là đầu vào của prompt tiếp theo. Điều này hiệu quả hơn việc cố gắng giải quyết mọi thứ trong một prompt khổng lồ và cho phép bạn xác thực kết quả trung gian trước khi tiếp tục.
Add error handling to this file upload function. Consider:
- File size limits
- Invalid file types
- Network interruptions during upload
- Disk space errors
- Concurrent upload conflicts
- Partial upload cleanup
Use try-catch with specific error types. Add retry logic for
transient failures. Return meaningful error messages to the client.Prompt Engineering Cho Các Công Cụ Khác Nhau
Ví dụ, thay vì một prompt duy nhất để "xây dựng hệ thống xác thực người dùng", hãy chain: (1) thiết kế schema cơ sở dữ liệu, (2) tạo mô hình người dùng, (3) triển khai logic đăng ký, (4) triển khai logic đăng nhập, (5) thêm middleware xác thực, (6) viết kiểm thử cho từng component. Mỗi bước xây dựng trên các bước trước đó và bạn có thể xem xét và tinh chỉnh từng bước.
Prompt Engineering Cho Claude
Retrieval-Augmented Generation (RAG) kết hợp mô hình AI với cơ sở kiến thức bên ngoài. Thay vì chỉ dựa vào kiến thức được huấn luyện của mô hình, RAG truy xuất tài liệu, mã hoặc dữ liệu liên quan và đưa chúng vào prompt dưới dạng ngữ cảnh. Điều này đặc biệt có giá trị khi làm việc với codebase, tài liệu nội bộ hoặc domain-specific knowledge mà mô hình không được huấn luyện.
Implement a user avatar upload feature for a Next.js 14 application.
Tech stack: Next.js App Router, TypeScript, Prisma, PostgreSQL, AWS S3
Requirements:
- Accept JPEG, PNG, WebP (max 5MB)
- Resize to 200x200 and 400x400 thumbnails using Sharp
- Upload originals to S3 with unique keys
- Store S3 URLs in the User model
- Delete old avatar when uploading a new one
- Return presigned URLs for frontend display
Acceptance criteria:
- Invalid file types return 400 with error message
- Files over 5MB return 413
- Successful upload returns 200 with avatar URLs
- Old avatars are cleaned up from S3
Create: API route, service layer, Prisma schema update, and types.Prompt Engineering Cho GitHub Copilot và Cursor
Nhiều công cụ lập trình AI triển khai RAG tự động bằng cách lập chỉ mục codebase của bạn và truy xuất tệp liên quan khi bạn đặt câu hỏi. Bạn có thể tăng cường điều này bằng cách duy trì tài liệu dự án tốt, sử dụng quy ước đặt tên nhất quán và giữ cho cấu trúc codebase của bạn rõ ràng và có tổ chức.
Design a RESTful API for a project management application.
Architecture: Express.js with TypeScript, following clean architecture
Auth: JWT with refresh token rotation
Versioning: URL-based (/api/v1/)
Response format: { success: boolean, data?: T, error?: { code, message } }
Endpoints needed:
- Projects CRUD with team membership
- Tasks CRUD with assignee, priority, status
- Comments on tasks with mentions
- Activity feed (recent actions across projects)
Include:
- Request/response TypeScript interfaces
- Zod validation schemas
- Error handling middleware
- Pagination for list endpoints (cursor-based)Prompt Engineering Cho Codex CLI
Các công cụ AI khác nhau có đặc điểm, thế mạnh và định dạng prompt tối ưu khác nhau. Dưới đây là cách điều chỉnh prompt engineering cho từng công cụ chính.
Design a Prisma schema for an e-commerce platform with these entities:
- Users (authentication, profile, addresses)
- Products (variants, categories, inventory)
- Orders (line items, status history, payments)
- Reviews (ratings, images, helpful votes)
- Cart (items, applied coupons)
Requirements:
- Use PostgreSQL with UUID primary keys
- Soft deletes with deletedAt timestamps
- Proper indexes for common query patterns
- Enums for order status, payment status
- Decimal fields for prices (not float)
- Full-text search on product name and description
- Include a migration filePrompt Engineering Cho Lập Trình
ChatGPT (đặc biệt là GPT-4o) xuất sắc trong các cuộc trò chuyện lặp lại, nơi bạn tinh chỉnh đầu ra qua nhiều vòng. Bắt đầu với prompt tổng quan, sau đó thu hẹp dần. Sử dụng các cuộc trò chuyện riêng biệt cho các chủ đề khác nhau để giữ ngữ cảnh tập trung. ChatGPT phản hồi tốt với phân vai, hướng dẫn định dạng và yêu cầu tự đánh giá ("xem xét câu trả lời của bạn và xác định bất kỳ điểm yếu hoặc giả định nào").
Create a reusable DataTable component in React with TypeScript.
Styling: Tailwind CSS + shadcn/ui conventions
Features:
- Column definitions with sort, filter, and custom renderers
- Server-side pagination with page size selector
- Row selection (single and multi) with checkboxes
- Loading skeleton state
- Empty state with custom message
- Responsive: card layout on mobile, table on desktop
Accessibility:
- Keyboard navigation (arrow keys, Enter, Escape)
- Screen reader announcements for sort and filter changes
- ARIA labels on all interactive elements
Props interface:
- data, columns, isLoading, pagination, onSort, onFilter, onSelect
Include a usage example with a user list table.Prompt Engineering Cho DevOps
Đối với đầu ra dài, hãy yêu cầu ChatGPT tạo dàn ý trước, sau đó điền vào từng phần. Điều này tạo ra kết quả có cấu trúc và toàn diện hơn so với yêu cầu mọi thứ cùng một lúc. Đối với các nhiệm vụ lập trình, ChatGPT hoạt động tốt nhất khi bạn cung cấp mã hiện có và yêu cầu sửa đổi cụ thể thay vì yêu cầu tạo từ đầu.
Create a Docker Compose setup for a development environment with:
- Next.js app (hot reload enabled)
- PostgreSQL 16 with persistent volume
- Redis for session storage
- MinIO (S3-compatible) for local file storage
Requirements:
- All services on a shared network
- Environment variables from .env file
- Health checks for all services
- Volumes for node_modules (avoid bind mount issues)
- PostgreSQL initialized with seed data
- Non-root containers where possible
Also create:
- Dockerfile for the Next.js app (multi-stage build)
- .env.example with all required variables
- Makefile with common commands (up, down, logs, reset-db)Prompt Engineering Theo Miền
Claude (thông qua Claude Code hoặc giao diện Anthropic) xuất sắc trong phân tích dài và suy luận tỉ mỉ. Nó có xu hướng thận trọng và kỹ lưỡng hơn ChatGPT, khiến nó đặc biệt phù hợp cho code review, phân tích bảo mật và quyết định kiến trúc. Claude phản hồi tốt với ngữ cảnh chi tiết và hướng dẫn rõ ràng về những gì không nên làm.
Prompt Engineering Cho Phân Tích Dữ Liệu
Claude Code sử dụng tệp CLAUDE.md cho ngữ cảnh dự án liên tục. Đầu tư thời gian để tạo tệp này toàn diện, bao gồm stack công nghệ, quy ước mã hóa, framework kiểm thử, mẫu kiến trúc và bất kỳ hướng dẫn tùy chỉnh nào. Tệp CLAUDE.md hoạt động như một system prompt liên tục, đảm bảo tính nhất quán trên tất cả các phiên.
# Step 1: Design the architecture
"Design the architecture for a real-time chat application.
List the components, their responsibilities, and how they
communicate. Use a diagram-like text format."
# Step 2: Define the data model
"Based on the architecture above, design the database schema
for the chat application. Include users, conversations,
messages, and read receipts. Use Prisma schema format."
# Step 3: Implement the API
"Implement the REST API for the chat application based on
the architecture and schema we designed. Start with the
message endpoints: send, list, delete."
# Step 4: Add WebSocket support
"Now add WebSocket support for real-time message delivery.
Use Socket.io. Integrate with the existing message API."
# Step 5: Write tests
"Write integration tests for the chat API and WebSocket
events using Jest and Supertest."GitHub Copilot và Cursor cung cấp hoàn thiện mã nội tuyến và khả năng chat trong IDE. Đối với hoàn thiện nội tuyến, prompt hiệu quả nhất là chính mã bạn đang viết — Copilot phân tích các tệp xung quanh và dự đoán những gì bạn cần tiếp theo. Viết tên hàm mô tả, comment và chữ ký kiểu rõ ràng để hướng dẫn đề xuất của Copilot.
Prompt Engineering Cho Sáng Tạo Nội Dung
Đối với tính năng chat trong IDE, hãy điều trị chúng như cuộc trò chuyện với lập trình viên cấp cao quen thuộc với codebase của bạn. Tham chiếu tệp và hàm cụ thể, giải thích những gì bạn đang cố gắng đạt được và chỉ định bất kỳ ràng buộc nào. Cả hai công cụ đều có thể xem codebase của bạn, vì vậy hãy tận dụng điều này bằng cách yêu cầu thay đổi nhận thức ngữ cảnh thay vì đoạn mã chung chung.
{
await this.db.query('UPDATE users SET email = $1 WHERE id = $2', [email, id]);
await this.cache.del(`user:${id}`);
}
}
```
Here is the User type:
```typescript
interface User {
id: string;
email: string;
name: string;
role: 'admin' | 'user';
createdAt: Date;
}
```
Now, add an updateProfile method that allows updating name and email,
with validation that the email is not already taken by another user. Codex CLI hoạt động trong terminal và xuất sắc trong việc tạo mã nhanh, thao tác nhiều tệp và thực thi lệnh shell. Prompt hiệu quả cho Codex CLI là trực tiếp và hướng đến hành động, tập trung vào những gì bạn muốn đạt được thay vì giải thích dài dòng. Sử dụng cờ --file để cung cấp ngữ cảnh cụ thể và --model để chọn mô hình phù hợp cho nhiệm vụ.
Sử Dụng Bảng Prompt
Codex CLI xuất sắc khi bạn cung cấp ví dụ về mã hiện có và yêu cầu sửa đổi hoặc mở rộng. Nó cũng xử lý tốt các yêu cầu chuyển đổi ngôn ngữ — cung cấp tệp nguồn và chỉ định ngôn ngữ đích, và Codex sẽ dịch trong khi vẫn duy trì chức năng và các mẫu idiomatic.
Build a URL shortener API with these constraints:
MUST:
- Use Node.js 20+ with native fetch (no axios)
- Use PostgreSQL via pg driver (no ORM)
- Generate short codes of exactly 7 characters
- Support custom aliases (max 20 chars)
- Return 301 for existing short URLs
- Rate limit to 100 creates per hour per IP
MUST NOT:
- Use any ORM or query builder
- Store full URLs without normalization
- Allow short codes that conflict with existing routes
- Return database errors to the client
PERFORMANCE:
- Handle 10,000 requests per second
- Cache hot URLs in Redis with 5-minute TTL
- P99 latency under 50ms for redirectsTiêu Chí Đánh Giá
Các lĩnh vực khác nhau yêu cầu các chiến lược prompt engineering khác nhau. Dưới đây là cách điều chỉnh cách tiếp cận của bạn cho các ngữ cảnh cụ thể.
Analyze this codebase and provide the output in this exact format:
## Architecture Overview
[2-3 paragraph summary]
## Component Diagram
```mermaid
graph TD
[components and relationships]
```
## API Endpoints
| Method | Path | Description | Auth |
|--------|------|-------------|------|
## Database Tables
| Table | Columns | Indexes | Relations |
|-------|---------|---------|-----------|
## Recommendations
1. [Priority] [Description] - [Estimated effort]
2. ...
## Technical Debt
- [ ] [Description] - [Impact: High/Medium/Low]A/B Testing Prompt
Đối với lập trình, hãy chỉ định ngôn ngữ, framework, phiên bản và bất kỳ thư viện nào bạn muốn sử dụng. Đề cập đến các mẫu hiện có trong codebase của bạn, quy ước đặt tên và phong cách mã hóa. Yêu cầu kiểm thử cùng với mã triển khai và yêu cầu xử lý lỗi và trường hợp biên. Đối với các thay đổi phức tạp, hãy yêu cầu kế hoạch triển khai trước khi viết mã.
# Iteration 1: Get a starting point
"Write a rate limiter middleware for Express.js"
# Iteration 2: Add specificity
"Good start. Now modify it to use Redis for distributed
rate limiting across multiple server instances. Use sliding
window instead of fixed window."
# Iteration 3: Add edge cases
"Add handling for: Redis connection failures (fall back to
in-memory), custom rate limits per route, burst allowance
for legitimate traffic spikes, and proper headers
(X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset)."
# Iteration 4: Add tests
"Write comprehensive tests for all the scenarios we've
covered, including Redis failures and burst handling."Đối với DevOps, hãy chỉ định nhà cung cấp cloud, công cụ CI/CD và yêu cầu hạ tầng. Đề cập đến các ràng buộc bảo mật, yêu cầu tuân thủ và kỳ vọng về khả năng mở rộng. Yêu cầu tài liệu và hướng dẫn khắc phục sự cố cùng với script triển khai.
Kiểm Tra và Tối Ưu Hóa Prompt
Đối với phân tích dữ liệu, hãy chỉ định định dạng dữ liệu, kích thước và cấu trúc. Đề cập đến các công cụ ưa thích (pandas, SQL, Excel) và các loại phân tích bạn cần. Yêu cầu giải thích cùng với kết quả và yêu cầu trực quan hóa khi phù hợp.
Prompt engineering là gì?
Đối với sáng tạo nội dung, hãy chỉ định đối tượng, giọng điệu, độ dài và định dạng. Cung cấp ví dụ về phong cách ưa thích, đề cập đến các điểm chính cần bao gồm và chỉ định bất kỳ điểm nào cần tránh. Yêu cầu dàn ý trước khi viết nội dung đầy đủ.
- Đối với các vấn đề kỹ thuật: "hãy phân tích vấn đề này, xác định nguyên nhân tiềm ẩn, sau đó đề xuất giải pháp."
- Đối với quyết định thiết kế: "liệt kê các cách tiếp cận khả thi, đánh giá ưu nhược điểm của từng cách, sau đó đề xuất cách tiếp cận phù hợp nhất cho tình huống này."
- Đối với gỡ lỗi: "truy tìm luồng thực thi qua mã này, xác định nơi hành vi có thể sai lệch so với mong đợi và đề xuất cách sửa."
- Sử dụng chính xác các thư viện và phiên bản cụ thể
- Tuân theo các quy ước đặt tên và phong cách mã hóa cụ thể
# Effective GPT-4 prompt structure
**Role:** Senior TypeScript developer
**Task:** Implement a JWT authentication middleware
**Context:** Express.js API, PostgreSQL, existing User model
**Constraints:** No external auth libraries, use crypto module
**Output:** Complete, production-ready code with types
**Format:** Single file with inline comments for complex logicPrompt engineering có phải là kỹ năng kỹ thuật?
Kiểm tra prompt có hệ thống là điều phân biệt người dùng AI bình thường với người thực hành prompt engineering. Đối xử với prompt của bạn như mã — kiểm tra, lặp lại và tối ưu hóa.
- Xử lý các trường hợp biên và điều kiện lỗi
- Đáp ứng các yêu cầu về hiệu suất hoặc bảo mật
- Tương thích với các ràng buộc môi trường hoặc triển khai
- Đối với JSON: "trả về kết quả dưới dạng mảng JSON của đối tượng với các trường: id (string), name (string), score (number)."
- Đối với Markdown: "định dạng phản hồi của bạn dưới dạng tài liệu markdown với tiêu đề h2 cho các phần chính và h3 cho các phần phụ."
# Effective Claude Code prompt
Read the following files to understand the current architecture:
- src/routes/userRoutes.ts
- src/middleware/authMiddleware.ts
- src/models/User.ts
Then refactor the authentication flow to support:
1. JWT access tokens (15 min expiry) + refresh tokens (7 day expiry)
2. Token rotation on refresh (invalidate old refresh token)
3. Rate limiting on the refresh endpoint (5 per minute per user)
Update all related files and run the test suite when done.Prompt engineering có còn quan trọng khi AI cải thiện không?
Khi phát triển prompt cho nhiệm vụ quan trọng, hãy tạo bảng prompt so sánh các biến thể khác nhau. Kiểm tra cùng một nhiệm vụ với mức độ cụ thể, phân vai và ràng buộc khác nhau để xác định cách tiếp cận tối ưu. Lập tài liệu prompt nào hoạt động tốt nhất và lý do.
- Đối với mã: "viết mã bằng TypeScript với strict mode, sử dụng async/await và bao gồm JSDoc comment cho tất cả hàm public."
- Kỹ sư bảo mật để xem xét mã tìm lỗ hổng
- Kiến trúc sư cơ sở dữ liệu để thiết kế schema
- Nhà văn kỹ thuật để tạo tài liệu
- Chuyên gia hiệu suất để tối ưu hóa mã chậm
> {
// Copilot will generate the implementation based on these types Làm thế nào để viết prompt tốt cho ChatGPT?
Thiết lập tiêu chí đánh giá rõ ràng cho đầu ra AI: tính đúng đắn (đầu ra có chính xác về mặt thực tế không?), tính đầy đủ (có bao gồm tất cả các khía cạnh cần thiết không?), tính nhất quán (có nhất quán trên nhiều lần chạy không?), hiệu quả (có cần sửa đổi tối thiểu không?), và khả năng tái tạo (cùng một prompt có tạo ra kết quả chất lượng tương tự mỗi lần không?).
- Chuyên gia khả năng truy cập để xem xét UI component
- Lập trình viên senior để xem xét kiến trúc
- Prompt 1: Phân tích cấu trúc codebase hiện tại và xác định nơi xác thực nên được tích hợp.
- Prompt 2: Thiết kế schema cơ sở dữ liệu cho bảng người dùng và bảng phiên.
- Prompt 3: Triển khai logic đăng ký người dùng với xác thực đầu vào.
# Effective Cursor prompt
@src/services/paymentService.ts @src/types/payment.ts
Refactor the processPayment function to use the Strategy pattern.
Create separate strategy classes for each payment provider
(Stripe, PayPal, BankTransfer). The function should accept a
payment method and delegate to the appropriate strategy.
Keep the same public API so existing callers don't break.Prompt engineering có hoạt động với tất cả mô hình AI không?
Giống như A/B testing trong phát triển web, bạn có thể so sánh có hệ thống các prompt khác nhau cho cùng một nhiệm vụ. Tạo hai hoặc nhiều biến thể prompt, chạy mỗi biến thể nhiều lần, ghi điểm kết quả dựa trên tiêu chí đánh giá của bạn và chọn prompt có hiệu suất tốt nhất. Điều này đặc biệt có giá trị cho prompt sẽ được sử dụng lặp lại hoặc bởi nhiều thành viên trong nhóm.
- Prompt 4: Triển khai logic đăng nhập với băm mật khẩu và quản lý phiên.
- Prompt 5: Thêm middleware xác thực để bảo vệ route.
- Prompt 6: Viết unit test và integration test cho tất cả component.
- Đối với prompt lập trình: "Bạn là một lập trình viên senior TypeScript. Tôi đang làm việc trên một ứng dụng Next.js 14 sử dụng Prisma cho ORM và Zod để xác thực. Quy ước của chúng tôi là sử dụng functional component, ưu tiên Server Component khi có thể, và sử dụng async/await. Vui lòng..."
- Đối với prompt DevOps: "Bạn là một kỹ sư DevOps quản lý hạ tầng AWS. Chúng tôi sử dụng Terraform cho infrastructure as code, GitHub Actions cho CI/CD, và Docker để container hóa. Yêu cầu bảo mật của chúng tôi bao gồm..."
Câu Hỏi Thường Gặp
Sẵn sàng áp dụng những kỹ thuật này vào thực tế? Khám phá bộ sưu tập công cụ AI và tài nguyên lập trình của ToolHub để tăng năng suất của bạn.
Vague Instructions
Prompt engineering là kỹ năng thiết kế hướng dẫn cho mô hình AI để tạo ra đầu ra chất lượng cao. Nó liên quan đến việc tạo prompt rõ ràng, có ngữ cảnh và có cấu trúc khai thác khả năng tốt nhất từ các công cụ như ChatGPT, Claude và GitHub Copilot. Prompt engineering tốt có thể cải thiện đáng kể chất lượng, độ chính xác và mức độ liên quan của nội dung do AI tạo ra.
# Bad
"Fix the login bug"
# Good
"Fix the bug where users with uppercase emails cannot log in.
The issue is in src/auth/login.ts - the email comparison is
case-sensitive but emails are stored in lowercase in the database.
The fix should normalize the email to lowercase before comparison."Missing Context
Prompt engineering là một kỹ năng kết hợp hiểu biết kỹ thuật với giao tiếp rõ ràng. Mặc dù nó không yêu cầu kỹ năng lập trình truyền thống cho các trường hợp sử dụng cơ bản, nhưng prompt engineering hiệu quả cho các nhiệm vụ kỹ thuật (lập trình, DevOps, phân tích dữ liệu) yêu cầu kiến thức miền. Các khía cạnh kỹ thuật bao gồm hiểu khả năng và hạn chế của mô hình, thiết kế prompt có cấu trúc và kiểm tra có hệ thống.
# Bad
"Write a function to send emails"
# Good
"Write an email sending function for our NestJS application.
We use:
- @nestjs/mailer with Handlebars templates
- SMTP via AWS SES
- Templates stored in src/templates/emails/
- Existing MailService class in src/mail/mail.service.ts
The function should accept a template name, recipient, and
template variables. Include error handling for SES throttling
and bounce notifications."Overloading Prompts
Có, prompt engineering vẫn quan trọng và có thể sẽ vẫn quan trọng trong tương lai gần. Mặc dù các mô hình AI đang cải thiện trong việc hiểu ý định, nhưng chúng không thể đọc được suy nghĩ của bạn. Khoảng cách giữa những gì bạn muốn và những gì bạn nói vẫn tồn tại, và prompt engineering thu hẹp khoảng cách đó. Khi AI trở nên mạnh mẽ hơn, chi phí của prompt kém càng tăng lên — bạn có thể nhận được kết quả kém nhanh hơn.
# Bad - Too many tasks in one prompt
"Build a complete user management system with authentication,
profile management, email verification, password reset,
role-based access control, and an admin dashboard"
# Good - Break it into focused prompts
Prompt 1: "Design the database schema for a user management system..."
Prompt 2: "Implement the authentication endpoints..."
Prompt 3: "Add email verification flow..."
Prompt 4: "Implement role-based access control middleware..."Ignoring Output Format
Prompt ChatGPT hiệu quả là cụ thể, giàu ngữ cảnh và có cấu trúc. Chỉ định vai cho AI, cung cấp thông tin nền, nêu rõ yêu cầu và ràng buộc của bạn, chỉ định định dạng đầu ra mong muốn và yêu cầu AI giải thích quá trình suy luận cho các vấn đề phức tạp.
# Bad
"List all the API endpoints"
# Good
"List all API endpoints in a markdown table with these columns:
| Method | Path | Description | Auth Required | Request Body | Response |"Not Iterating
Các nguyên tắc prompt engineering cốt lõi (tính cụ thể, ngữ cảnh, ràng buộc, định dạng đầu ra) áp dụng phổ quát trên tất cả mô hình AI. Tuy nhiên, mỗi mô hình có thế mạnh, điểm yếu và hành vi tối ưu riêng. Các kỹ thuật nâng cao như few-shot prompting và chain-of-thought prompting hoạt động trên hầu hết các mô hình hiện đại, nhưng hiệu quả của chúng có thể khác nhau.
# Instead of accepting the first response, iterate:
"Good start. Now add input validation using Zod schemas."
"Now add proper error handling with custom error classes."
"Now add logging for all operations."
"Now write tests for all the edge cases we've discussed."Prompt Templates Library
Here are ready-to-use prompt templates for common developer tasks. Copy these templates, fill in the placeholders, and adapt them to your specific needs. Each template combines multiple prompting techniques for maximum effectiveness.
Template 1: Feature Implementation
You are a senior {language} developer specializing in {framework}.
Implement {feature_description} for our {project_type} application.
Tech stack:
- {language} {version} with {framework} {version}
- {database} for data storage
- {orm} for database access
- {testing_framework} for tests
Requirements:
- {requirement_1}
- {requirement_2}
- {requirement_3}
Constraints:
- Must follow existing patterns in the codebase
- Must include input validation
- Must handle errors gracefully
- Must be backward compatible
Output:
1. Implementation code with inline comments for complex logic
2. Unit tests covering happy path and edge cases
3. Brief explanation of design decisionsTemplate 2: Bug Investigation
You are a debugging specialist with expertise in {language}/{framework}.
Investigate and fix this bug:
**Symptom:** {describe_the_observed_behavior}
**Expected:** {describe_the_expected_behavior}
**Frequency:** {always/sometimes/under_specific_conditions}
**Environment:** {production/staging/development}
Relevant code:
```
{paste_relevant_code}
```
Error output / stack trace:
```
{paste_error_output}
```
Think step by step:
1. Identify the root cause
2. Explain why this bug occurs
3. Provide the fix with code
4. Suggest how to prevent similar bugs
5. Write a regression testTemplate 3: Code Review
You are a senior code reviewer at a {company_type} company.
Review this {language} code for:
1. **Correctness:** Logic errors, off-by-one errors, null handling
2. **Security:** Injection, XSS, auth bypasses, data exposure
3. **Performance:** N+1 queries, unnecessary allocations, missing caches
4. **Maintainability:** Code smells, naming, complexity
5. **Testing:** Missing test cases, brittle tests
Code to review:
```
{paste_code}
```
For each issue found, provide:
- Severity: 🔴 Critical / 🟡 Warning / 🔵 Info
- Category: Which of the 5 areas above
- Description: What's wrong and why
- Suggestion: How to fix it, with code example
End with an overall assessment and top 3 priorities.Template 4: API Endpoint Design
Design a {http_method} {endpoint_path} endpoint for {resource_description}.
Framework: {framework}
Auth: {auth_method}
Database: {database}
The endpoint should:
- {functionality_1}
- {functionality_2}
- {functionality_3}
Provide:
1. Route definition with middleware chain
2. Request validation schema ({validation_library})
3. Controller/handler function
4. Service layer function
5. Database query/function
6. Response types (success and error)
7. Example curl request and responseTemplate 5: Database Migration
Create a database migration for {change_description}.
Current schema:
```
{current_schema}
```
Desired changes:
- {change_1}
- {change_2}
ORM: {orm_name}
Database: {database_type}
Requirements:
- Migration must be reversible (include down migration)
- Preserve existing data (write data migration SQL if needed)
- Add appropriate indexes for new columns
- Consider performance impact on large tables
- Include rollback safety checksTemplate 6: Test Suite Generation
Write a comprehensive test suite for {function_or_class_name}.
Testing framework: {framework}
Mocking library: {library}
Code under test:
```
{paste_code}
```
Test categories to cover:
- ✅ Happy path: All valid inputs produce correct outputs
- 🔄 Edge cases: Empty inputs, boundary values, null/undefined
- ❌ Error cases: Invalid inputs, permission denied, network failures
- 🏎️ Performance: Response time expectations for critical paths
- 🔒 Security: Auth checks, input sanitization
For each test:
- Use descriptive test names that read like documentation
- Follow Arrange-Act-Assert pattern
- Include setup/teardown for shared state
- Mock external dependenciesTemplate 7: Refactoring Plan
You are a software architect specializing in {language} refactoring.
Current code:
```
{paste_current_code}
```
Problems with current code:
- {problem_1}
- {problem_2}
Refactor using {pattern_or_principle}.
Provide:
1. **Analysis:** What's wrong and why the current approach doesn't scale
2. **Target Architecture:** How the refactored code should be structured
3. **Step-by-step Plan:** Ordered refactoring steps (safe, incremental)
4. **Refactored Code:** Complete implementation
5. **Migration Guide:** How to transition from old to new without breaking changes
6. **Risk Assessment:** What could go wrong and how to mitigateTemplate 8: Documentation Generation
Generate documentation for this {language} code:
```
{paste_code}
```
Documentation type: {JSDoc/TSDoc/Python docstrings/README section}
Requirements:
- Document all public functions/classes/methods
- Include parameter descriptions with types
- Include return type descriptions
- Add usage examples for non-obvious APIs
- Note any side effects or important caveats
- Use {style_guide} conventions
For README documentation, include:
- Overview (1-2 paragraphs)
- Installation instructions
- Quick start example
- API reference table
- Configuration optionsTemplate 9: Performance Optimization
You are a performance engineering specialist.
Analyze and optimize this code for performance:
```
{paste_code}
```
Current performance:
- {metric}: {current_value}
- Target: {target_value}
- Bottleneck suspected at: {location}
Optimization constraints:
- Must not change the public API
- Must maintain all existing test passes
- Must not sacrifice readability for micro-optimizations
- {additional_constraint}
Provide:
1. **Profiling Analysis:** Where time/memory is being spent
2. **Optimization Strategies:** Ranked by expected impact
3. **Optimized Code:** With comments explaining each change
4. **Benchmark Comparison:** Before vs after expected metrics
5. **Trade-offs:** Any readability or complexity costsTemplate 10: Security Audit
You are a security engineer specializing in {language}/{framework} security.
Perform a security audit on this code:
```
{paste_code}
```
Check for:
- Injection attacks (SQL, NoSQL, command, LDAP)
- Authentication and authorization bypasses
- Cross-site scripting (XSS) vulnerabilities
- Cross-site request forgery (CSRF) exposure
- Insecure direct object references (IDOR)
- Sensitive data exposure (logging, error messages)
- Insecure cryptography or key management
- Race conditions in concurrent operations
- Denial of service vulnerabilities
For each finding:
- Severity: Critical / High / Medium / Low
- OWASP Category: Which Top 10 category
- Description: Clear explanation of the vulnerability
- Attack Scenario: How an attacker would exploit it
- Remediation: Specific code fix
- Verification: How to confirm the fix worksReady to supercharge your development workflow with AI? Explore ToolHub's curated collection of AI coding assistants, prompt optimization tools, and developer productivity utilities — all free and ready to use.
Khám Phá Công Cụ AIFrequently Asked Questions
What is prompt engineering and why is it important for developers?
Prompt engineering is the practice of crafting effective instructions for AI language models to produce desired outputs. For developers, it matters because the quality of AI-generated code, debugging assistance, and documentation directly depends on how well you communicate your intent. Small changes in prompt wording, structure, and context can dramatically improve output quality, turning vague or incorrect responses into precise, useful code and explanations. As AI tools become central to development workflows, prompt engineering is becoming as fundamental as knowing how to write a good bug report or code review comment.
What are the most important prompting techniques for developers?
The most important prompting techniques include: zero-shot prompting (direct instructions without examples), few-shot prompting (providing examples to guide output format), chain-of-thought prompting (asking the AI to reason step by step), role-playing prompts (assigning a persona like "act as a senior engineer"), and system prompts (setting persistent instructions). Combining these techniques with specific commands like "step by step," "think aloud," and "review and critique" produces the best results for coding tasks. The key is to match the technique to the task — use chain-of-thought for debugging, role-playing for expert-level advice, and few-shot for consistent formatting.
How do I write better prompts for AI coding assistants?
To write better prompts: be specific about your tech stack and requirements, provide relevant code context, specify the desired output format, break complex tasks into smaller steps, use role assignment to set expertise level, include constraints and edge cases, and iterate on your prompts when the first result isn't perfect. Avoid vague instructions, missing context, and overloading a single prompt with too many tasks. The most impactful improvement most developers can make is simply providing more context — share the relevant code, types, and project structure before asking your question.
Which AI coding tool is best for prompt engineering?
The best tool depends on your use case. ChatGPT and GPT-4 excel at conversational debugging and explanation. Claude and Claude Code are ideal for large-context tasks and agentic workflows where the AI needs to understand an entire codebase. GitHub Copilot provides the best inline code completion in IDEs. Cursor offers deep IDE integration with multi-file awareness and file references. Codex CLI is great for terminal-based code generation. Most developers benefit from using multiple tools together, each for its strengths — Copilot for inline completion, Claude Code for multi-file tasks, and ChatGPT for learning and explanation.
What are common mistakes to avoid when prompting AI for code?
Common mistakes include: using vague instructions like "fix this" without context, failing to specify your tech stack or framework version, overloading a single prompt with too many unrelated tasks, not specifying the desired output format (JSON, markdown, etc.), accepting the first response without iterating, and not providing enough code context for the AI to understand your project structure. The single biggest mistake is insufficient context — always share relevant code, types, and project details before asking your question. Always iterate and refine your prompts for better results.
Can prompt engineering replace traditional coding skills?
No, prompt engineering complements traditional coding skills but cannot replace them. You need to understand programming concepts, architecture patterns, and system design to write effective prompts and evaluate AI output. Prompt engineering helps you leverage AI tools more effectively, but you still need the expertise to recognize when AI output is incorrect, insecure, or suboptimal. Think of it as a multiplier on your existing skills — a senior engineer with good prompting skills will always outperform a junior developer with the same prompting skills because they can provide better context and evaluate output quality.
How do I handle AI hallucinations in code generation?
AI hallucinations — when the model generates plausible but incorrect code — are a real concern. To mitigate them: always review generated code before using it, run tests to verify correctness, ask the AI to explain its reasoning (chain-of-thought prompting), provide specific library versions and documentation references, and cross-check API usage against official documentation. When the AI references a function or method you're not familiar with, verify it exists before using it. For critical code (security, financial, medical), always have a human expert review the output thoroughly.