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

第 8 課:寫 Prompt for Code 的藝術 — 從模糊到精確

良好程式碼提示的剖析:上下文、限制、範例。提示模式:程式碼的零樣本、少樣本、思考鏈。如何清楚描述需求。迭代提示。常見錯誤以及如何修復它們。

💻 程式設計 — 第 8 課 第 8 課:寫 Prompt for Code 的藝術 — 從模糊到精確

使用 GitHub Copilot 進行 Vibe 編碼:從基礎知識到高級

第 3 部分:快速程式碼工程

亞洲開發網

1. 為什麼即時工程對 Vibe Coding 很重要?

在 Vibe 編碼中, 提示是你的程式碼。輸出品質直接取決於提示品質。好的提示可以節省迭代時間,而壞的提示會導致完全錯誤的程式碼。

❌ 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. 剖析良好的程式碼提示

有效的提示代碼有 5 個組成部分:

┌─────────────────────────────────────────────────┐
│           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ả           │
│                                                  │
└─────────────────────────────────────────────────┘

應用實例:

// 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. 代碼提示模式

3.1.零射擊-零例如

// Đơ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.很少的鏡頭-有例子

// 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.思考鏈-逐步推理

// 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.基於角色-為 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. 迭代提示-逐步改進

有效的振動編碼就是其中之一 談話,沒有任何提示:

// 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. 常見錯誤及其解決方法

錯誤 例如 修復
太模糊了 “製作一個儀表板” 指定指標、圖表、資料來源、佈局
太長 1 個提示超過 500 個單字 分為多次迭代
沒有上下文 “新增身份驗證” 指定框架、策略、現有程式碼
自相矛盾 “使用 REST 但實時” 顯而易見:REST + WebSocket 實作即時
無限制 “創建 API” 指定錯誤處理、身份驗證、驗證
越南語和英語 “創建一個函數來檢查有效性” 一致性:全英語或全越南語

6. 提供提示模板

範本:新功能

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

範本:錯誤修復

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]

模板:重構

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. 提示中的英語與越南語

AI模型(GPT、Claude)主要以英語訓練,因此:

  • 英文提示 通常可以為程式碼提供更好的結果
  • 越南語提示 適用於:解釋、文件、評論
  • 混合 (越南語 + 代碼術語英語)也適用於 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.

八、總結

圖案 何時使用
零射擊 任務簡單明了
少射 需要按照特定模式輸出
思想鏈 複雜的邏輯、設計決策
基於角色 安全審查、程式碼審查、特定專業知識
迭代 每個任務(應該始終使用)

下一篇文章會更深入 情境管理 — 如何為人工智慧提供正確的上下文來理解您的程式碼庫。