A01: Claude Code 的提示工程
在 Claude Code 中编写提示(Prompt)与在聊天机器人中编写提示有本质区别。在浏览器中与 Claude 对话时,你是在为文本生成精心组织文字。而在使用 Claude Code 时,你是在向一个拥有工具、能进行多步决策并在真实文件系统上操作的 Agent 发出指令。本附录介绍让 Claude Code 高效工作的特定模式。
为什么 Claude Code 的提示方式不同
在聊天界面中,你的提示是 Claude 接收的唯一输入。在 Claude Code 中,你的提示只是众多输入之一:
Claude Code 的完整上下文:
┌──────────────────────────────────────┐
│ System prompt (Claude Code's core) │ ← 你无法控制
│ CLAUDE.md (your project rules) │ ← 你控制(第 2 章)
│ Memory files (saved preferences) │ ← Claude 管理
│ Tool definitions (Read, Write, etc.) │ ← 你无法控制
│ Conversation history │ ← 你们共同构建
│ Your current prompt │ ← 你控制
│ Tool results (file contents, etc.) │ ← 工具生成
└──────────────────────────────────────┘这意味着你的提示不需要承载全部上下文。CLAUDE.md 处理项目规范,记忆文件处理你的偏好,工具结果处理实际代码。你的提示只需要说明做什么以及为什么。
具体性光谱
每个提示都落在从模糊到过度约束的光谱上。最佳区域取决于你的任务:
太模糊(无效)
Fix the bug.问题:Claude 不知道哪个 bug、在哪里找、或者"修复"是什么样子。它会浪费工具调用随机探索代码库。
太约束(低效)
Open src/auth/middleware.ts at line 42. Change the if statement from
`if (token.expired)` to `if (token.expired || !token.valid)`. Then open
src/auth/types.ts and add a `valid: boolean` field to the Token interface
on line 15. Then run npm test.问题:你已经完成了所有思考。如果你已经确切知道要改什么,那直接自己改就好。你只是把 Claude 当打字助手,而不是推理伙伴。
恰到好处(有效)
Users are reporting 401 errors when their JWT token has been rotated but the
old token hasn't expired yet. The issue is likely in the auth middleware
(src/auth/). Find where we validate tokens and add a check for token
validity beyond just expiration. Run the auth tests to verify.为什么有效:
- 做什么:修复 Token 轮换时的 401 错误
- 在哪里:
src/auth/目录(缩小搜索范围) - 为什么:缺少 Token 有效性检查(解释根本原因)
- 如何验证:运行 auth 测试(定义成功标准)
- 未指定的部分:具体文件、行号、实现细节 -- Claude 自行解决
Claude Code 的五种提示模式
模式 1:调查型提示
当你需要 Claude 在行动前先理解问题时使用。
I'm seeing intermittent 500 errors in production. The error logs mention
a "connection pool exhausted" message from the database layer.
Investigate:
1. Find where we configure the database connection pool
2. Check if there's connection leak potential (connections opened but not closed)
3. Look at the middleware chain for anything that might hold connections open
4. Report your findings before making any changes关键要素:
- 描述症状,而非解决方案
- 要求 Claude 在修改前先汇报
- 给出起点但不限定调查路径
模式 2:实现型提示
当你希望 Claude 构建某个具体功能时使用。
Add rate limiting to the /api/upload endpoint:
- Max 10 uploads per user per minute
- Return 429 with retry-after header when exceeded
- Use the existing Redis instance for tracking (REDIS_URL is in .env)
- Follow the pattern in src/middleware/auth.ts for middleware structure
- Add tests
Don't modify any existing endpoints.关键要素:
- 带有具体数字的明确需求
- 指向现有模式("参照 src/middleware/auth.ts 的模式")
- 显式边界("不要修改任何现有端点")
- 包含测试要求
模式 3:审查型提示
当你希望 Claude 只分析不修改时使用。
Review the changes on this branch (feature/payments) for:
1. Security issues (especially around payment data handling)
2. Error handling gaps (what happens when Stripe API is down?)
3. Missing tests for edge cases
Don't fix anything — just list the findings with severity ratings.关键要素:
- 具体的审查维度(不只是"审查一下")
- 显式的"不要修复"指令(否则 Claude 会尝试修复)
- 要求严重度评级以帮助优先排序
模式 4:重构型提示
当你希望 Claude 重组现有代码时使用。
The user authentication logic is split across 4 files with duplicated
validation. Consolidate into a single auth service:
- Keep the public API unchanged (same function signatures)
- Extract shared validation into private methods
- Don't change the database schema
- Run existing tests to verify nothing breaks关键要素:
- 描述当前问题(重复代码)
- 描述目标状态(单一服务)
- 约束条件("保持公共 API 不变")
- 验证步骤("运行现有测试")
模式 5:探索型提示
当你在学习一个代码库或技术时使用。
I just joined this project. Walk me through the architecture:
1. What's the tech stack? (read package.json, go.mod, or equivalent)
2. How is the code organized? (describe the directory structure)
3. Where's the main entry point?
4. How does a request flow from the API layer to the database?
5. What testing patterns are used?关键要素:
- 开放但有结构
- 编号问题(Claude 逐一回答)
- 从宏观到具体
反模式:不应该做的事
反模式 1:"要小心"
Be very careful when making changes. Double-check everything. Make sure
you don't break anything. Be extra cautious.为什么无效:这些是情绪化的指令,不是可操作的。Claude 没有"小心模式"。应该告诉 Claude 具体注意什么:
Before committing: run the test suite, check for TypeScript errors with
tsc --noEmit, and verify the API responses haven't changed shape.反模式 2:过早抽象请求
Create a flexible, extensible framework for handling all possible
authentication scenarios. It should support OAuth, SAML, JWT, API keys,
and any future auth methods.为什么无效:Claude 会过度工程化,构建一个无人需要的庞大抽象。应该针对当前需求来构建:
Add JWT authentication to the /api/users endpoint. Use the jsonwebtoken
package. Store the secret in process.env.JWT_SECRET.反模式 3:串联不相关的任务
Fix the login bug, then add a dark mode toggle, then update the README,
then review the PR from last week.为什么无效:上下文腐化(Context Rot)。当 Claude 到达任务 4 时,它已经忘记了任务 1 的细节。参见 A02 上下文工程。应该每个会话只做一个任务,或在不相关任务之间使用 /clear。
反模式 4:引用 Claude 没有的外部知识
Implement the solution from that Stack Overflow answer we discussed yesterday.为什么无效:Claude 没有其他工具(浏览器、Slack 等)中对话的记忆。应该提供实际内容:
Implement this approach for handling race conditions:
[paste the specific approach, not just a link]常见任务的提示模板
Bug 修复模板
Bug: [describe the symptom]
Expected: [what should happen]
Actual: [what happens instead]
Reproduce: [steps or test case]
Suspected area: [file or module, if known]
Find the root cause, fix it, and add a regression test.功能实现模板
Feature: [one-sentence description]
Requirements:
- [requirement 1]
- [requirement 2]
- [requirement 3]
Constraints:
- [what NOT to change]
- [performance/security requirements]
Pattern to follow: [reference existing code]
Verify: [how to test]代码审查模板(管道模式)
git diff main..HEAD | claude -p "Review these changes:
1. Correctness: any logic bugs?
2. Security: any vulnerabilities (OWASP top 10)?
3. Performance: any N+1 queries, unnecessary re-renders, or memory leaks?
4. Style: anything inconsistent with the existing codebase?
Rate each category: PASS / CONCERN / FAIL. Explain any non-PASS ratings."工具调用上下文中的思维链
在聊天机器人中,思维链(Chain-of-Thought)意味着"在回答前逐步思考"。在 Claude Code 中,思维链通过工具调用循环自然发生:
- Claude 阅读提示并决定需要什么信息
- 它调用 Read/Glob/Grep 收集上下文
- 每次工具结果返回后,它完善对问题的理解
- 最终执行操作(Write/Edit/Bash)
你可以增强这种自然的思维链,通过在提示中鼓励先调查再行动:
Before implementing anything:
1. Read the existing tests to understand what's expected
2. Check if there's a similar feature elsewhere in the codebase
3. Plan the approach and tell me before you start coding
Then implement.这种"调查、规划、实现"的结构在 第 15 章 生产工作流 中被正式化为 R-P-E-R-S 工作流。
提示中的 Token 效率
你的提示在 Claude Code 的上下文中占比很小,但它决定了后续一切的方向。结构良好的提示会减少工具调用次数、降低上下文消耗并产生更好的结果。
高效:直接指向正确位置
The rate limiter config is in src/config/rate-limits.ts. Increase the
/api/upload limit from 10 to 25 per minute.Claude 读取一个文件,做一次编辑。总计约 500 Token。
低效:让 Claude 自己搜索
Somewhere in the config files there's a rate limit setting. Find it and change it.Claude 搜索多个文件,读取多个配置。总计约 3,000 Token。
两者产生相同结果,但高效提示使用的 Token 少 6 倍。当你知道东西在哪里时,直接说明。当你不知道时也没关系,但要承认:
I'm not sure where the rate limit config lives. Check src/config/ first,
then the middleware directory.核心要点
- 你的提示只是众多输入之一 -- CLAUDE.md、记忆文件和工具结果承载了大部分上下文。保持提示聚焦于"做什么"和"为什么"。
- 描述症状而非解决方案,用于调查类任务。让 Claude 利用工具找到答案。
- 指向现有模式来请求实现。"参照 src/auth/middleware.ts 的模式"比指定每个细节更有效。
- 每个会话一个任务(或在不相关任务之间使用
/clear),以避免上下文腐化。 - 要求 Claude 在行动前先调查,用于复杂任务。通过工具调用产生的自然思维链比直接跳到实现效果更好。
- "要小心"不可操作。用具体的验证步骤替代情绪化的指令。
另见:A02 上下文工程 了解如何管理完整的上下文预算,以及 A05 工具调用内部机制 了解 Claude 如何选择使用哪个工具。