AI 提示词工程:开发者必备命令与技巧
提示词工程已成为使用 AI 工具的开发者最关键的技能之一。无论你使用的是 ChatGPT、Claude、GitHub Copilot 还是 Cursor,提示词的质量直接决定了 AI 输出的质量。一个精心设计的提示词可以将模糊、无用的响应转化为精确、可用于生产环境的代码。本综合指南涵盖了从基础提示技巧到高级策略、各工具专属技巧以及即用模板的所有内容,帮助你从每次 AI 交互中获得最大价值。
什么是提示词工程?
提示词工程是为 AI 语言模型精心设计有效指令以产生预期输出的艺术与科学。其核心在于沟通——学习如何用 AI 模型最理解的语言来表达。正如高级开发者会给初级开发者更精确的指示以获得更好的结果,提示词工程教你如何以清晰和精准的方式向 AI 系统传达你的意图。
对于开发者而言,提示词工程之所以重要,是因为 AI 编程助手已成为现代开发工作流不可或缺的一部分。这些工具可以生成代码、调试问题、编写测试、重构架构和解释复杂系统——但前提是你给出了正确的指令。一个写得不好的提示词可能产生能编译但不符合你意图的代码,使用了错误的框架版本,或忽略了关键的边界情况。相比之下,一个精心设计的提示词可以产生与经验丰富的开发者编写的代码无异的输出。
提示词的微小变化会产生巨大的影响。比较一下"修复 bug"和"修复 UserService.authenticate 方法中当 email 参数为 undefined 时出现的空引用异常。该方法位于 src/services/UserService.ts,使用 bcrypt 进行密码比较"之间的区别。第一个提示词几乎没有给 AI 提供任何有用信息。第二个提供了清晰的问题描述、位置和上下文——使 AI 能够在第一次尝试时就产生精确、正确的修复。
基础提示技巧
理解核心提示技巧为你奠定了基础。每种技巧都有其擅长的特定用例,经验丰富的提示词工程师通常会在单个提示词中组合多种技巧以达到最佳效果。
零样本提示
零样本提示是最简单的提示形式——你直接给 AI 一个指令,不提供任何示例。AI 完全依赖其训练数据和提示词中的信息来生成响应。这种技巧适用于所需输出格式显而易见的简单任务,或 AI 在训练中见过许多类似示例的情况。
Write a Python function that validates an email address using regex.
The function should return True for valid emails and False for invalid ones.零样本提示对于常见的、定义明确的任务很有效。然而,当你需要特定的输出格式、风格或方法时,少样本提示会更加可靠。
少样本提示
少样本提示涉及在给出实际任务之前,提供一个或多个期望的输入-输出模式示例。这种技巧非常强大,因为它精确展示了你想要什么,减少了歧义并引导 AI 朝向正确的格式和风格。AI 从你的示例中学习模式,并将其应用于新输入。
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_id少样本提示在你需要一致的格式、特定的编码规范,或 AI 可能做出不符合你项目风格的假设时特别有价值。通常两到三个示例就足以建立清晰的模式。
思维链提示
思维链提示要求 AI 在给出最终答案之前逐步推理问题。这种技巧显著提高了复杂任务的准确性,因为它迫使 AI 处理中间步骤,而不是跳到可能不正确的结论。研究表明,在提示词中添加"think step by step"可以在推理任务上将准确性提高 30-50%。
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]思维链提示对于调试、架构决策和任何需要逻辑推理的任务都是必不可少的。通过要求 AI 展示其推理过程,你还获得了验证其推理和发现中间步骤错误的能力。
角色扮演提示
角色扮演提示为 AI 分配特定的角色或专业水平,这会影响其响应的深度、风格和重点。当你告诉 AI "扮演高级 DevOps 工程师"时,它会转变视角,提供更注重运维、更适合生产环境的建议,而不是通用的代码片段。这种技巧利用了 AI 在领域特定内容上的训练来产生更专家级的输出。
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.有效角色扮演的关键在于具体性。"扮演 Python 开发者"太模糊了。"扮演专注于使用 Apache Airflow 和 pandas 构建高性能数据管道的 Python 开发者"给了 AI 更清晰的参考框架。
系统提示词与用户提示词
大多数 AI 工具区分系统提示词和用户提示词。系统提示词设置适用于整个对话的持久指令,而用户提示词是单独的消息。理解这种区别对于在长时间交互中保持一致性至关重要。
CLAUDE.md 文件充当持久的系统提示词。在 ChatGPT 中,你可以设置自定义指令作为所有对话的系统提示词。
# 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.开发者必备 AI 命令
某些命令模式在所有主要 AI 编程工具中都证明非常有效。这些不是字面命令,而是持续触发高质量响应的指令短语。将它们视为激活 AI 模型特定能力的力量词汇。
| 命令 | 用途 | 最佳场景 |
|---|---|---|
| "Act as..." / "You are a..." | 角色分配 | 获取领域专家级响应 |
| "Step by step" | 思维链 | 复杂推理和调试 |
| "Think aloud" | 推理透明化 | 理解 AI 的决策过程 |
| "Explain like I'm 5" | 简化解释 | 快速学习新概念 |
| "Review and critique" | 代码审查 | 获取建设性的代码反馈 |
| "Write tests for" | 测试生成 | 全面的测试覆盖 |
| "Refactor using..." | 基于模式的重构 | 应用设计模式 |
| "Find bugs in" | 调试 | 识别隐藏问题 |
| "Convert from X to Y" | 代码翻译 | 语言或框架迁移 |
| "Document this" | 文档生成 | 创建内联文档和 README |
| "Optimize for performance" | 优化 | 提升速度和效率 |
| "Add error handling" | 健壮性增强 | 使代码达到生产就绪 |
"Act as..." / "You are a..." — 角色分配
角色分配是提示词工程中最强大的命令之一。通过指定角色,你激活了领域特定知识,并设定了对响应深度和风格的期望。角色越具体,输出越好。
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 charges"Step by step" — 思维链
在提示词中添加"step by step"或"let's think step by step"会触发 AI 分解其推理过程。这对于调试、算法设计和架构决策特别有效。逐步方法不仅产生更好的结果,还使 AI 的推理透明化,让你能够发现逻辑错误。
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;"Think aloud" — 推理透明化
"Think aloud"类似于"step by step",但更侧重于 AI 的决策过程。它要求 AI 叙述其推理,包括考虑了哪些替代方案以及为什么选择特定方法。当你需要了解设计决策中的权衡,或想评估 AI 的推理是否合理时,这非常有价值。
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."Explain like I'm 5" — 简化解释
当学习新概念或试图理解复杂代码时,"explain like I'm 5"(ELI5)去除了术语,提供了直观的、基于类比的解释。这对于加入新项目、理解不熟悉的代码库或向非技术利益相关者解释技术概念特别有用。
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."Review and critique" — 代码审查
使用"review and critique"信号 AI 采取批判性视角,而不是简单地接受代码。这会产生更彻底的分析,包括潜在的 bug、安全问题、性能问题和风格违规。就像按需获得高级工程师的代码审查。
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]"Write tests for" — 测试生成
测试生成是 AI 编程工具最高价值的使用之一。通过指定"write tests for"以及你的测试框架和覆盖期望,你可以快速生成全面的测试套件。关键是指定边界情况和测试优先级。
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."Refactor using..." — 基于模式的重构
在重构提示词中指定设计模式或原则给了 AI 明确的目标架构。与其使用模糊的"重构这个"请求,命名模式会产生遵循既定软件工程原则的专注、一致的重构。
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]"Find bugs in" — 调试
"Find bugs in"命令激活 AI 的分析模式,促使其寻找问题而不是生成代码。当你提供代码、描述预期行为并提及观察到的症状时,效果最佳。
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]"Add error handling" — 健壮性增强
许多 AI 生成的代码片段在正常路径上可以工作,但缺乏适当的错误处理。"Add error handling"命令专门针对这一差距,要求 AI 考虑故障模式、边界情况和恢复策略。
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.代码生成的提示模式
除了单个命令,某些提示模式对于特定类型的代码生成任务已被证明特别有效。这些模式将角色分配、上下文提供和输出规范等技巧组合成结构化提示,持续产生高质量结果。
功能实现提示
在实现新功能时,最有效的提示词遵循类似规范的结构:描述功能、指定技术栈、定义验收标准并提及任何约束。这给了 AI 需要构建什么的完整图景。
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.API 设计提示
API 设计提示词受益于预先指定架构风格、认证方法、版本策略和响应格式。这确保生成的 API 一致并遵循你项目的约定。
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)数据库 Schema 提示
数据库 Schema 提示词应指定 ORM、命名约定、索引策略和关系。AI 可以生成带有适当约束、索引和迁移文件的完整 Schema。
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 fileUI 组件提示
对于 UI 组件,指定框架、样式方法、可访问性要求和交互状态比通用的"创建组件"提示词产生更好的结果。
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.配置与 DevOps 提示
DevOps 和配置提示词应指定目标环境、安全要求和任何组织标准。这防止 AI 生成不符合你基础设施的通用配置。
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)高级提示策略
一旦你掌握了基础技巧和命令,这些高级策略将帮助你处理超越单个提示词能力的复杂、多步骤开发任务。
提示链
提示链将复杂任务分解为一系列更小、更专注的提示词,每个提示词建立在前一个的输出之上。这种策略比试图在单个庞大提示词中完成所有事情产生更好的结果,因为每一步都获得了 AI 的全部注意力和上下文。
# 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."有效提示链的关键是确保每一步在进入下一步之前产生完整、可用的输出。审查每个输出,必要时进行修正,然后将精炼的结果输入下一个提示词。
上下文填充
上下文填充涉及在提问之前向 AI 提供所有相关的代码、文档和上下文。虽然这似乎显而易见,但许多开发者跳过了这一步,然后纳闷为什么 AI 做出了错误的假设。你提供的相关上下文越多,AI 的响应就越准确和具体。
{
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. 注意提供现有代码和类型如何使 AI 能够生成与现有模式完全一致的方法,使用相同的缓存策略,并遵循现有的类型定义。
约束规范
设置显式约束防止 AI 做出不希望的假设。约束定义了 AI 不应该做什么,这通常与它应该做什么同样重要。常见约束包括技术版本、性能要求、安全规则和编码标准。
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 redirects输出格式控制
指定所需的输出格式确保 AI 的响应无需重新格式化即可立即使用。当输出需要被其他工具解析、插入文档或用作配置文件时,这尤其重要。
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]迭代优化
迭代优化是通过后续提示词逐步改进 AI 输出的实践。第一次响应很少是完美的,但它提供了一个可以优化的起点。每次迭代比试图在单个提示词中做到完美更高效地接近期望结果。
# 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."这种迭代方法比编写单个庞大提示词更有效,因为每次迭代允许你根据 AI 的先前输出进行纠偏和添加细节。它反映了你与人类开发者合作的方式:从粗略实现开始,然后优化。
各工具专属提示技巧
虽然上述技巧适用于所有 AI 工具,但每个平台都有独特的优势和特点。调整你的提示风格以适应每个工具的特性可以显著改善结果。
ChatGPT / GPT-4
ChatGPT 和 GPT-4 擅长对话式交互,受益于结构化、组织良好的提示词。它们很好地处理长上下文,特别擅长解释概念和生成文档。
- 使用自定义指令:在 ChatGPT 的自定义指令中设置你的技术栈和偏好,这样你就不必在每次对话中重复。
- 利用 Code Interpreter:对于数据分析任务,要求 ChatGPT 使用 Code Interpreter 运行 Python 代码并生成可视化。
- 在提示词中使用 markdown 格式:GPT-4 对带有标题、项目符号和代码块的结构化提示词响应良好。
- 指定响应长度:GPT-4 倾向于冗长。当你需要简洁时,添加"be concise"或"in under 200 words"。
- 使用系统消息:在 API 中,使用系统消息来设置编码标准和项目上下文等持久指令。
# 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 logicClaude / Claude Code
Claude 和 Claude Code 在理解大型代码库、遵循复杂指令和产生结构良好的输出方面特别强。Claude Code 的代理能力使其非常适合多步骤任务。
- 使用 CLAUDE.md:这是你能做的最有影响力的事情。将你的项目上下文、约定和偏好放在 CLAUDE.md 中。
- 明确指定文件位置:Claude Code 在你指定要读取和修改的文件时效果最佳。
- 让它运行命令:Claude Code 可以执行测试和构建命令。要求它通过运行测试来验证其工作。
- 在长会话中使用 /compact:当上下文变长时,使用 /compact 压缩对话同时保留最重要的信息。
- 利用 XML 标签:Claude 对提示词中 XML 标记的部分响应良好,可以清晰划分请求的不同部分。
# 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.GitHub Copilot
GitHub Copilot 的运行方式不同于基于聊天的工具——它在你输入时提供内联建议。有效的 Copilot 使用依赖于编写通过注释、类型签名和周围上下文清晰传达意图的代码。
- 编写描述性注释:在函数前添加如 // Validate email format and check for duplicates 的注释,给 Copilot 明确的意图。
- 使用 TypeScript 类型:定义良好的类型和接口引导 Copilot 朝向正确的实现。
- 在注释中提供示例:在注释中展示预期的输入/输出,帮助 Copilot 匹配你想要的格式。
- 接受部分建议:有时 Copilot 结构正确但细节有误。接受建议然后编辑细节。
- 对复杂任务使用 Copilot Chat:对于多文件更改或架构决策,使用 Copilot Chat 而不是内联建议。
> {
// Copilot will generate the implementation based on these types Cursor
Cursor 将 IDE 集成与 AI 聊天功能相结合,提供内联补全和了解你代码库的聊天界面。其优势在于深度项目感知和引用特定文件与符号的能力。
- 使用 @file 引用:用 @filename 引用特定文件,给 Cursor 精确的上下文。
- 使用 @codebase 获取广泛上下文:当你需要 Cursor 搜索整个项目时,使用 @codebase。
- 使用 @docs 获取库文档:Cursor 可以用 @docs 引用第三方库文档。
- 利用 Cmd+K 进行内联编辑:选择代码并使用 Cmd+K 用自然语言描述更改。
- 设置项目规则:使用 .cursorrules 文件(类似于 CLAUDE.md)设置持久的项目指令。
# 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.Codex CLI
Codex CLI 是 OpenAI 的基于终端的编程代理,概念上类似于 Claude Code。它擅长从命令行执行多步骤开发任务。
- 提供明确目标:Codex CLI 在有明确的高层目标时效果最佳,而不是逐步指令。
- 指定工作目录:确保你从正确的项目根目录运行 Codex CLI。
- 先使用提案模式:在让 Codex 做出更改之前,使用提案模式审查其计划。
- 谨慎设置沙箱权限:通过配置沙箱权限来控制 Codex 可以执行什么。
- 迭代输出:与其他工具一样,第一次尝试可能需要通过后续提示词进行优化。
常见错误及避免方法
即使是有经验的开发者也会犯这些常见的提示错误。认识并避免它们将立即改善你的 AI 交互。
模糊指令
最常见的错误是提供模糊、不够具体的指令。像"修复这个"、"让它更好"或"添加功能"这样的提示词几乎没有给 AI 提供任何有用信息。AI 会做出假设,而这些假设通常不符合你的意图。
# 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."缺少上下文
AI 模型不知道你的项目,除非你告诉它们。未能提供相关上下文——你的技术栈、框架版本、现有代码模式或项目结构——迫使 AI 猜测,而且往往猜错。始终包含新团队成员理解你的请求所需的上下文。
# 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."提示词过载
试图在单个提示词中完成太多不相关的任务会导致各方面都平庸的结果。AI 的注意力被分散,它可能跳过某些任务的重要细节,同时过度关注其他任务。将复杂请求分解为专注的、顺序的提示词。
# 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..."忽略输出格式
当你需要特定格式的输出——JSON、markdown、特定文件结构——未指定这一点会导致不可预测的格式。AI 可能在你需要 JSON 时返回散文,或在需要多个文件时返回单个文件。始终明确指定所需的输出格式。
# 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 |"不进行迭代
不经优化就接受 AI 的第一次响应是一个错失的机会。第一次响应提供了一个你可以通过后续提示词改进的基础。迭代是 AI 辅助开发真正力量所在——每个周期都产生更好、更精炼的输出。
# 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."提示词模板库
以下是常见开发者任务的即用提示词模板。复制这些模板,填入占位符,并根据你的具体需求进行调整。每个模板组合了多种提示技巧以达到最大效果。
模板 1:功能实现
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 decisions模板 2:Bug 调查
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 test模板 3:代码审查
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.模板 4:API 端点设计
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 response模板 5:数据库迁移
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 checks模板 6:测试套件生成
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 dependencies模板 7:重构计划
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 mitigate模板 8:文档生成
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 options模板 9:性能优化
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 costs模板 10:安全审计
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 works准备好用 AI 超级驱动你的开发工作流了吗?探索 ToolHub 精选的 AI 编程助手、提示词优化工具和开发者生产力工具集——全部免费,随时可用。
探索 AI 工具常见问题
什么是提示词工程,为什么对开发者很重要?
提示词工程是为 AI 语言模型精心设计有效指令以产生预期输出的实践。对于开发者而言,它之所以重要,是因为 AI 生成代码、调试辅助和文档的质量直接取决于你传达意图的程度。提示词措辞、结构和上下文的微小变化可以显著改善输出质量,将模糊或错误的响应转化为精确、有用的代码和解释。随着 AI 工具成为开发工作流的核心,提示词工程正变得像知道如何写好 bug 报告或代码审查评论一样基础。
开发者最重要的提示技巧有哪些?
最重要的提示技巧包括:零样本提示(不提供示例的直接指令)、少样本提示(提供示例以引导输出格式)、思维链提示(要求 AI 逐步推理)、角色扮演提示(分配角色如"扮演高级工程师")和系统提示词(设置持久指令)。将这些技巧与"step by step"、"think aloud"和"review and critique"等特定命令组合,可以为编程任务产生最佳结果。关键是将技巧与任务匹配——调试使用思维链,专家级建议使用角色扮演,一致格式使用少样本。
如何为 AI 编程助手写出更好的提示词?
要写出更好的提示词:具体说明你的技术栈和需求,提供相关代码上下文,指定所需的输出格式,将复杂任务分解为更小的步骤,使用角色分配设定专业水平,包含约束和边界情况,并在第一次结果不完美时迭代优化你的提示词。避免模糊指令、缺少上下文和在单个提示词中塞入太多任务。大多数开发者可以做出的最有影响力的改进就是提供更多上下文——在提问之前分享相关代码、类型和项目结构。
哪个 AI 编程工具最适合提示词工程?
最佳工具取决于你的用例。ChatGPT 和 GPT-4 擅长对话式调试和解释。Claude 和 Claude Code 适合需要理解整个代码库的大上下文任务和代理工作流。GitHub Copilot 在 IDE 中提供最佳的内联代码补全。Cursor 提供深度 IDE 集成,具有多文件感知和文件引用能力。Codex CLI 适合基于终端的代码生成。大多数开发者受益于组合使用多个工具,各取所长——Copilot 用于内联补全,Claude Code 用于多文件任务,ChatGPT 用于学习和解释。
向 AI 提示代码时应避免哪些常见错误?
常见错误包括:使用"修复这个"等模糊指令而不提供上下文,未能指定你的技术栈或框架版本,在单个提示词中塞入太多不相关任务,未指定所需的输出格式(JSON、markdown 等),不经迭代就接受第一次响应,以及没有为 AI 提供足够的代码上下文来理解你的项目结构。最大的错误是上下文不足——始终在提问之前分享相关代码、类型和项目详情。始终迭代和优化你的提示词以获得更好的结果。
提示词工程能取代传统编程技能吗?
不,提示词工程补充传统编程技能但不能取代它们。你需要理解编程概念、架构模式和系统设计才能写出有效的提示词并评估 AI 输出。提示词工程帮助你更有效地利用 AI 工具,但你仍然需要专业知识来识别 AI 输出何时是不正确的、不安全的或次优的。将其视为你现有技能的乘数——具有良好提示技巧的高级工程师总是优于具有相同提示技巧的初级开发者,因为他们可以提供更好的上下文并评估输出质量。
如何处理 AI 代码生成中的幻觉问题?
AI 幻觉——即模型生成看似合理但不正确的代码——是一个真实的担忧。缓解方法包括:始终在使用前审查生成的代码,运行测试以验证正确性,要求 AI 解释其推理(思维链提示),提供特定的库版本和文档参考,并根据官方文档交叉检查 API 用法。当 AI 引用你不熟悉的函数或方法时,在使用前验证它是否存在。对于关键代码(安全、金融、医疗),始终让人类专家彻底审查输出。