Claude Code 的提示词工程
2026/7/31 15:01:36 · 更新于 2026/7/31 15:06:24
从源码与架构视角彻底拆解 Claude Code 摒弃“单一超长 System Prompt”的设计哲学,通过动态装配的六大层级、CLI干预机制及底层工具路由规则,构建出一套高度模块化且能实时响应的现代 AI Agent 提示词运行机制。
Claude Code 的提示词工程并非依赖一段“终极 System Prompt”,而是基于一套分层装配的动态提示词系统。该体系将基础身份、会话状态、运行时环境、工具规范与多 Agent 协作规则解耦为独立模块,并在执行时按当前上下文动态拼装。理解这一架构,是掌握 Claude Code 行为逻辑、路由策略与自定义扩展机制的核心。

第一层:主会话的 System Prompt(基础身份与任务边界)
Claude Code 最核心的提示词入口位于 constants/prompts.ts。源码中定义了最基础的初始引导段:
function getSimpleIntroSection(outputStyleConfig: OutputStyleConfig | null): string {
return `
You are an interactive agent that helps users ${
outputStyleConfig !== null
? 'according to your "Output Style" below, which describes how you should respond to user queries.'
: 'with software engineering tasks.'
} Use the instructions below and the tools available to you to assist the user.
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming.`
}
中文释义:你是一个交互式智能体,负责帮助用户完成软件工程任务(或按下方“Output Style”配置响应)。请结合下面的指令和可用工具来协助用户。重要:除非你能确定某个 URL 确实是在帮助用户完成编程任务,否则绝不能为用户凭空生成或猜测 URL。
这段 Prompt 严格划定了四层逻辑:
- 确立基础身份:交互式 Agent(非纯聊天机器人)
- 锚定任务域:软件工程
- 声明交互前提:工具可用
- 设定安全边界:严禁无依据生成 URL
这构成了 Claude Code 的总纲提示词,决定了其后续所有行为的上限。
第二层:System Prompt 的动态分段拼装
Claude Code 拒绝将系统提示词写死为超长固定模板,而是通过运行时动态拼接多个独立 Section:
const dynamicSections = [
systemPromptSection('session_guidance', () =>
getSessionSpecificGuidanceSection(enabledTools, skillToolCommands),
),
systemPromptSection('memory', () => loadMemoryPrompt()),
systemPromptSection('env_info_simple', () =>
computeSimpleEnvInfo(model, additionalWorkingDirectories),
),
systemPromptSection('language', () =>
getLanguageSection(settings.language),
),
systemPromptSection('output_style', () =>
getOutputStyleSection(outputStyleConfig),
),
DANGEROUS_uncachedSystemPromptSection(
'mcp_instructions',
() => isMcpInstructionsDeltaEnabled() ? null : getMcpInstructionsSection(mcpClients),
'MCP servers connect/disconnect between turns',
),
]
该机制至少包含以下核心模块:
- 会话指导 (session_guidance)
- 记忆层 (memory)
- 基础环境信息 (env_info_simple)
- 语言偏好 (language)
- 输出风格配置 (output_style)
- MCP 服务器连接指令 (mcp_instructions)
执行逻辑对比: ❌ 传统模式:把一段固定 system prompt 塞给模型。 ✅ Claude Code 机制:根据当前会话状态,动态拼装出当前这一轮最合适的 system prompt。
这也是其工程化程度远超普通“复制提示词”类 AI 工具的根本原因。

第三层:用户定制入口(替换 vs 追加)
CLI 层在 main.tsx 暴露了两种明确的 Prompt 注入参数:
addOption(new Option('--system-prompt <prompt>', 'System prompt to use for the session').argParser(String))
addOption(new Option('--append-system-prompt <prompt>', 'Append a system prompt to the default system prompt').argParser(String))
底层路由逻辑在 utils/queryContext.ts 中被严格区分:
// customSystemPrompt replaces the default system prompt entirely.
// appendSystemPrompt appends extra text after the default system prompt.
customSystemPrompt会完全替换默认系统提示词。appendSystemPrompt会在默认系统提示词后面追加额外内容。
工程价值:多数实际诉求并非“推翻默认 Prompt”,而是“在默认能力上叠加约束”。区分 replace 与 append 是典型的防御性设计,兼顾了深度定制与基线稳定性。
第四层:Teammate 模式的角色切换提示词
在多 Agent 协作(Agent Swarms)模式下,系统会自动向节点注入专属通信规范。当检测到团队会话时,main.tsx 会触发附加逻辑:
if (isAgentSwarmsEnabled() && storedTeammateOpts?.agentId && storedTeammateOpts?.agentName && storedTeammateOpts?.teamName) {
const addendum = getTeammatePromptAddendum().TEAMMATE_SYSTEM_PROMPT_ADDENDUM;
appendSystemPrompt = appendSystemPrompt ? `${appendSystemPrompt}
${addendum}` : addendum;
}
实际追加内容定义于 utils/swarm/teammatePromptAddendum.ts:
export const TEAMMATE_SYSTEM_PROMPT_ADDENDUM = `
# Agent Teammate Communication
IMPORTANT: You are running as an agent in a team. To communicate with anyone on your team:
- Use the SendMessage tool with \`to: "<name>"\` to send messages to specific teammates
- Use the SendMessage tool with \`to: "*"\` sparingly for team-wide broadcasts
Just writing a response in text is not visible to others on your team - you MUST use the SendMessage tool.
`
你正在以团队成员 Agent 的身份运行。如果你要和团队中的其他成员沟通:使用
SendMessage工具,并把to指向具体成员名字;只有在必要时才使用to: "*"进行全员广播。仅仅输出普通文本,团队里的其他成员是看不到的。你必须使用SendMessage工具。
本质:这不属于知识型提示词,而是角色切换与权限边界声明。它强制模型明确当前身份(Identity)、通信半径(Visibility Boundary)与交互协议。
第五层:工具级 Prompt 与路由策略控制
Claude Code 的工具不仅提供 JSON Schema,更内建了强约束的自然语言说明,直接干预模型的工具调用决策质量。
1. Read 工具(文件读取边界)
return `Reads a file from the local filesystem. You can access any file directly by using this tool.
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid.
Usage:
- The file_path parameter must be an absolute path, not a relative path
- By default, it reads up to 2000 lines starting from the beginning of the file
- This tool can only read files, not directories. To read a directory, use an ls command via the Bash tool.
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot, ALWAYS use this tool to view the file at the path.`
该 Prompt 的价值不在于声明“Read 工具存在”,而在于精准划定参数规范(必须绝对路径)、读取限制(默认 2000 行)、边界条件(只读文件不读目录需调用 Bash
ls)及多模态拦截规则(截图路径强制调用此工具)。
2. Bash 工具(防御性约束与路由策略)
tools/BashTool/prompt.ts 包含大量 Shell 行为限制,其中一条关键指令:
Do NOT use the Bash tool to run commands when a relevant dedicated tool is provided.
当已经提供了更合适的专用工具时,不要用 Bash 工具去执行命令。
此规则直接接管了模型的工具路由策略:读文件优先 Read → 文本搜索优先 Grep → 路径匹配优先 Glob → 退而求其次才调用 Bash。工具 Prompt 在此充当了隐式的策略控制器。
3. ExitPlanMode 工具(生命周期规范)
Plan Mode 同样拥有独立的约束 Prompt,核心目标非代码生成,而是规范“何时可结束规划”与“何时需交还用户决策”,确保主对话外的工具生命周期受控。
第六层:专项子系统与旁路调度提示词
Claude Code 后台运行着一套不直接暴露于主窗口的隐式 Prompt 网络,专门支撑侧向任务流:
/init初始化指令:并非随机生成CLAUDE.md,而是调用专属 Prompt 强制模型结构化输出项目结构、运行方式、常用命令、编码规范与协作约束,本质是自动化 Onboarding。- Tool Summary / Prompt Suggestion:用于压缩冗杂的 Tool Call 结果、生成后续轮次引导建议。此类提示词侧重系统内部上下文调度与冗余削减,虽用户不可见,却直接决定交互流畅度。
架构定位

Key takeaways
- 非静态文案,而是分层运行时:核心提示词、动态拼接层、工具约束与角色规范分离,随会话状态实时重组。
- 强路由策略控制:工具自带 Prompt 直接干预模型决策树(如 Bash 的降级使用原则、Read 的多模态拦截)。
- replace vs append 分离设计:CLI 明确区分“覆盖基线”与“叠加约束”,兼顾深度定制与系统稳定性。
- 隐性调度层决定体验:
/init、Tool Summary、Prompt Suggestion 等旁路提示词虽不可见,却主导初始化质量与上下文效率。 - 架构演进方向:Claude Code 已将 Prompt 工程从“文本编排”升级为“模块化运行时调度”,为复杂 Agent 协作奠定底层基础。
学习地图
Claude Code 提示词工程进阶地图
阶段一:认知重塑——从“文案”到“编译时装配”
- 目标理解为什么不存在一个放之四海而皆准的终极 System Prompt。
- 核心概念学习:分层体系 vs 单一超长模板;静态指令配置 vs 运行时动态拼装(Assembly)。
阶段二:剖析提示词核心模块 (Intro Section)
- 掌握 Anthropic 设定的底线安全约束、角色定义(交互式软件工程师Agent)及任务域划定。
- 动态分层注入机制:学习 Memory(记忆)、Env Info(环境信息)、Output Style 等组件如何基于当前会话状态被条件触发实时拼装。
阶段三:高级路由——角色切换与约束控制
- 多 Agent/Teammate协作提示词:理解附加 Prompt Addendum如何定义通信边界(如强制使用SendMessage而非自然文本沟通)。
- 工具级Prompt约束:挖掘内置Read、Bash工具自带的“策略性提示词”,解析它们如何规范工具的输入参数、操作红线及路由逻辑。
阶段四系统干预与应用实践
- CLI层面自定义:熟练使用 CLI参数的
--system-prompt(覆盖默认)与-append-system-prompt(在尾部追加约束)进行架构级调整。 - 应用实践
/initonboarding Prompt设计以及 Tool Summary/Context Pruning的上下文管理原理。
动手实践——分步指南
-
**初始化基础配置并验证追加机制(Append)**打开终端进入一个测试目录,执行
claude --append-system-prompt '在代码审查中请严格依据 Python PEP8规范提出具体修改建议'。观察模型在保留默认 AI Agent核心能力的同时,是否仅在输出细节上受限于该个性化约束。 -
测试全量替换系统提示词(Replace):尝试彻底接管底层引导逻辑运行 `claude --system-prompt '你目前仅是一名只会执行文件查询功能的纯辅助程序'输入需求。验证完全覆盖角色定义后的受限输出表现,体会两种机制的区别。
-
探索多 Agent/Teammate 模式通信约束(若环境支持):开启协同代理模式,并故意用普通文本尝试向虚拟 Teammate提问。验证预设的 Teammate Addendum Prompt是否成功激活了强制使用
SendMessage工具而非自然语法的交互边界。 -
模拟工具路由与红线测试在命令行中刻意制造一个本可用专用工具解决却被模型选错的场景(例如试图直接通过自然语言传递未处理的二进制路径)。观察底层 Bash/Read 工具自带的 Prompt 提示词如何触发安全拦截或自动重定向到正确的 API。
-
利用 CLI参数加载外部长策略文件:将复杂的规则约束整理进一个独立的
txt配置文件,使用官方支持的--system-prompt-file将其注入 Agent运行时的装配器,验证分层模块加载对超长上下文窗口的管理效率。
三大推荐资源
- 1Anthropic 官方文档:System Conditions & API Integration
Anthropic 针对 Claude API 和集成环境下的 System Prompt规范、上下文压缩及工具条件调用的权威技术指南。
https://docs.anthropic.com/en/docs/system-conditions
- 2Claude Code CLI Reference (Anthropic Docs)
关于 Claude Code 命令行界面的官方文档,详细记录了 `system-prompt`、`--append-system-prompt`等 CLI 选项的用法以及底层 Prompt注入机制。
https://code.claude.com/docs/en/cli-reference
- 3Anthropic Cookbook: Tool Use & Context Management
Anthropic 官方维护的开源教程库,提供了大量关于控制多轮交互以及设计模块化 system prompt的实际 Python/TS 案例模板。
https://github.com/anthropics/anthropic-cookbook/tree/main/tool_use
链接由 AI 推荐——使用前建议快速核实。