Claude Agent SDK 修改系统提示 - 输出样式 / Append / 自定义
学习如何使用三种方法自定义 Claude 的行为:输出样式、带 append 的 systemPrompt 和自定义系统提示。(原文为英文,已翻译)
系统提示定义 Claude 的行为、能力和响应风格。Claude Agent SDK 提供三种方式来自定义系统提示:使用输出样式(持久的、基于文件的配置)、追加到 Claude Code 的提示,或使用完全自定义的提示。
理解系统提示
系统提示是塑造 Claude 在整个对话中行为方式的初始指令集。
ℹ️ 默认行为: Agent SDK 默认使用最小系统提示。它只包含基本的工具指令,但省略了 Claude Code 的编码指南、响应样式和项目上下文。要包含完整的 Claude Code 系统提示,请在 TypeScript 中指定
systemPrompt: { type: "preset", preset: "claude_code" },或在 Python 中指定system_prompt={"type": "preset", "preset": "claude_code"}。
Claude Code 的系统提示包括:
- 工具使用说明和可用工具
- 代码风格和格式指南
- 响应语气和详细程度设置
- 安全和保护说明
- 当前工作目录和环境的上下文
修改方法
方法 1:CLAUDE.md 文件(项目级别说明)
CLAUDE.md 文件提供特定于项目的上下文和说明,当 Agent SDK 在目录中运行时会自动读取这些文件。它们作为项目的持久”记忆”。
CLAUDE.md 如何与 SDK 配合工作
位置和发现:
- 项目级别:
CLAUDE.md或.claude/CLAUDE.md在你的工作目录中 - 用户级别:
~/.claude/CLAUDE.md用于所有项目的全局说明
CLAUDE.md 文件在相应的设置源启用时读取:'project' 用于项目级 CLAUDE.md,'user' 用于 ~/.claude/CLAUDE.md。使用默认 query() 选项时,这两个源都启用,因此 CLAUDE.md 会自动加载。如果你显式设置 settingSources(TypeScript)或 setting_sources(Python),请包括你需要的源。CLAUDE.md 加载由设置源控制,而不是由 claude_code 预设控制。
内容格式: CLAUDE.md 文件使用纯 markdown,可包含:
- 编码指南和标准
- 项目特定的上下文
- 常用命令或工作流程
- API 约定
- 测试要求
CLAUDE.md 示例
# Project Guidelines
## Code Style
- Use TypeScript strict mode
- Prefer functional components in React
- Always include JSDoc comments for public APIs
## Testing
- Run `npm test` before committing
- Maintain >80% code coverage
- Use jest for unit tests, playwright for E2E
## Commands
- Build: `npm run build`
- Dev server: `npm run dev`
- Type check: `npm run typecheck`
在 SDK 中使用 CLAUDE.md
TypeScript
import { query } from "@anthropic-ai/claude-agent-sdk";
const messages = [];
for await (const message of query({
prompt: "Add a new React component for user profiles",
options: {
systemPrompt: {
type: "preset",
preset: "claude_code" // Use Claude Code's system prompt
},
settingSources: ["project"] // Loads CLAUDE.md from project
}
})) {
messages.push(message);
}
// Now Claude has access to your project guidelines from CLAUDE.md
Python
from claude_agent_sdk import query, ClaudeAgentOptions
messages = []
async for message in query(
prompt="Add a new React component for user profiles",
options=ClaudeAgentOptions(
system_prompt={
"type": "preset",
"preset": "claude_code", # Use Claude Code's system prompt
},
setting_sources=["project"], # Loads CLAUDE.md from project
),
):
messages.append(message)
# Now Claude has access to your project guidelines from CLAUDE.md
何时使用 CLAUDE.md
最适合:
- 团队共享上下文 - 每个人都应该遵循的准则
- 项目约定 - 编码标准、文件结构、命名模式
- 常用命令 - 项目特定的构建、测试、部署命令
- 长期记忆 - 应在所有会话中持续存在的上下文
- 版本控制说明 - 提交到 git 以便团队保持同步
关键特征:
- 在项目的所有会话中持久存在
- 通过 git 与团队共享
- 自动发现(不需要代码更改)
- 注意:如果你传递
settingSources: [],则不会加载
方法 2:输出样式(持久配置)
输出样式是修改 Claude 系统提示的已保存配置。它们存储为 markdown 文件,并可在会话和项目中重复使用。
创建输出样式
TypeScript
import { writeFile, mkdir } from "fs/promises";
import { join } from "path";
import { homedir } from "os";
async function createOutputStyle(name: string, description: string, prompt: string) {
// User-level: ~/.claude/output-styles
// Project-level: .claude/output-styles
const outputStylesDir = join(homedir(), ".claude", "output-styles");
await mkdir(outputStylesDir, { recursive: true });
const content = `---
name: ${name}
description: ${description}
---
${prompt}`;
const filePath = join(outputStylesDir, `${name.toLowerCase().replace(/\s+/g, "-")}.md`);
await writeFile(filePath, content, "utf-8");
}
// Example: Create a code review specialist
await createOutputStyle(
"Code Reviewer",
"Thorough code review assistant",
`You are an expert code reviewer.
For every code submission:
1. Check for bugs and security issues
2. Evaluate performance
3. Suggest improvements
4. Rate code quality (1-10)`
);
Python
from pathlib import Path
async def create_output_style(name: str, description: str, prompt: str):
# User-level: ~/.claude/output-styles
# Project-level: .claude/output-styles
output_styles_dir = Path.home() / ".claude" / "output-styles"
output_styles_dir.mkdir(parents=True, exist_ok=True)
content = f"""---
name: {name}
description: {description}
---
{prompt}"""
file_name = name.lower().replace(" ", "-") + ".md"
file_path = output_styles_dir / file_name
file_path.write_text(content, encoding="utf-8")
# Example: Create a code review specialist
await create_output_style(
"Code Reviewer",
"Thorough code review assistant",
"""You are an expert code reviewer.
For every code submission:
1. Check for bugs and security issues
2. Evaluate performance
3. Suggest improvements
4. Rate code quality (1-10)""",
)
使用输出样式
一旦创建,可通过以下方式激活输出样式:
- CLI:
/output-style [style-name] - 设置:
.claude/settings.local.json - 创建新的:
/output-style:new [description]
SDK 用户注意事项: 当你在选项中包含 settingSources: ['user'] 或 settingSources: ['project'](TypeScript)/ setting_sources=["user"] 或 setting_sources=["project"](Python)时,会加载输出样式。
方法 3:使用带 append 的 systemPrompt
你可以使用带 append 属性的 Claude Code 预设来添加你的自定义说明,同时保留所有内置功能。
TypeScript
import { query } from "@anthropic-ai/claude-agent-sdk";
const messages = [];
for await (const message of query({
prompt: "Help me write a Python function to calculate fibonacci numbers",
options: {
systemPrompt: {
type: "preset",
preset: "claude_code",
append: "Always include detailed docstrings and type hints in Python code."
}
}
})) {
messages.push(message);
if (message.type === "assistant") {
console.log(message.message.content);
}
}
Python
from claude_agent_sdk import query, ClaudeAgentOptions
messages = []
async for message in query(
prompt="Help me write a Python function to calculate fibonacci numbers",
options=ClaudeAgentOptions(
system_prompt={
"type": "preset",
"preset": "claude_code",
"append": "Always include detailed docstrings and type hints in Python code.",
}
),
):
messages.append(message)
if message.type == "assistant":
print(message.message.content)
改进跨用户和机器的提示缓存
默认情况下,即使两个会话使用相同的 claude_code 预设和 append 文本,如果它们从不同的工作目录运行,仍然无法共享提示缓存条目。这是因为预设在你的 append 文本之前在系统提示中嵌入了每个会话的上下文:工作目录、平台和操作系统版本、当前日期、git 状态和自动内存路径。该上下文中的任何差异都会产生不同的系统提示和缓存未命中。
要使系统提示在会话之间相同,请在 TypeScript 中设置 excludeDynamicSections: true,或在 Python 中设置 "exclude_dynamic_sections": True。每个会话的上下文移到第一个用户消息中,只在系统提示中留下静态预设和你的 append 文本,以便相同的配置在用户和机器之间共享缓存条目。
ℹ️
excludeDynamicSections需要@anthropic-ai/claude-agent-sdkv0.2.98 或更高版本,或 Python 的claude-agent-sdkv0.1.58 或更高版本。它仅适用于预设对象形式,当systemPrompt是字符串时无效。
以下示例将共享的 append 块与 excludeDynamicSections 配对,以便从不同目录运行的一组代理可以重用相同的缓存系统提示:
TypeScript
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Triage the open issues in this repo",
options: {
systemPrompt: {
type: "preset",
preset: "claude_code",
append: "You operate Acme's internal triage workflow. Label issues by component and severity.",
excludeDynamicSections: true
}
}
})) {
// ...
}
Python
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Triage the open issues in this repo",
options=ClaudeAgentOptions(
system_prompt={
"type": "preset",
"preset": "claude_code",
"append": "You operate Acme's internal triage workflow. Label issues by component and severity.",
"exclude_dynamic_sections": True,
},
),
):
...
权衡: 工作目录、git 状态和内存位置仍然到达 Claude,但作为第一个用户消息的一部分,而不是系统提示。用户消息中的指令在权重上比系统提示中的相同文本略轻,因此当 Claude 推理当前目录或自动内存路径时,它可能不太依赖它们。当跨会话缓存重用比最大权威的环境上下文更重要时,启用此选项。
有关非交互式 CLI 模式中的等效标志,请参阅 --exclude-dynamic-system-prompt-sections。
方法 4:自定义系统提示
你可以提供自定义字符串作为 systemPrompt,以完全用你自己的说明替换默认值。
TypeScript
import { query } from "@anthropic-ai/claude-agent-sdk";
const customPrompt = `You are a Python coding specialist.
Follow these guidelines:
- Write clean, well-documented code
- Use type hints for all functions
- Include comprehensive docstrings
- Prefer functional programming patterns when appropriate
- Always explain your code choices`;
const messages = [];
for await (const message of query({
prompt: "Create a data processing pipeline",
options: {
systemPrompt: customPrompt
}
})) {
messages.push(message);
if (message.type === "assistant") {
console.log(message.message.content);
}
}
Python
from claude_agent_sdk import query, ClaudeAgentOptions
custom_prompt = """You are a Python coding specialist.
Follow these guidelines:
- Write clean, well-documented code
- Use type hints for all functions
- Include comprehensive docstrings
- Prefer functional programming patterns when appropriate
- Always explain your code choices"""
messages = []
async for message in query(
prompt="Create a data processing pipeline",
options=ClaudeAgentOptions(system_prompt=custom_prompt),
):
messages.append(message)
if message.type == "assistant":
print(message.message.content)
四种方法的比较
| 特性 | CLAUDE.md | 输出样式 | 带 append 的 systemPrompt | 自定义 systemPrompt |
|---|---|---|---|---|
| 持久性 | 每个项目文件 | 保存为文件 | 仅会话 | 仅会话 |
| 可重用性 | 每个项目 | 跨项目 | 代码重复 | 代码重复 |
| 管理 | 在文件系统上 | CLI + 文件 | 在代码中 | 在代码中 |
| 默认工具 | 保留 | 保留 | 保留 | 丢失(除非包含) |
| 内置安全性 | 维护 | 维护 | 维护 | 必须添加 |
| 环境上下文 | 自动 | 自动 | 自动 | 必须提供 |
| 自定义级别 | 仅添加 | 替换默认 | 仅添加 | 完全控制 |
| 版本控制 | 与项目 | 是 | 与代码 | 与代码 |
| 范围 | 项目特定 | 用户或项目 | 代码会话 | 代码会话 |
注意: “with append” 表示在 TypeScript 中使用 systemPrompt: { type: "preset", preset: "claude_code", append: "..." },或在 Python 中使用 system_prompt={"type": "preset", "preset": "claude_code", "append": "..."}。
用例和最佳实践
何时使用 CLAUDE.md
最适合:
- 项目特定的编码标准和约定
- 记录项目结构和架构
- 列出常用命令(构建、测试、部署)
- 应进行版本控制的团队共享上下文
- 适用于项目中所有 SDK 用法的说明
示例:
- “所有 API 端点都应使用 async/await 模式”
- “提交前运行
npm run lint:fix” - “数据库迁移位于
migrations/目录中”
CLAUDE.md 文件在启用 project 设置源时加载,这是默认 query() 选项的默认设置。如果你显式设置 settingSources(TypeScript)或 setting_sources(Python),请包含 'project' 以继续加载项目级 CLAUDE.md。
何时使用输出样式
最适合:
- 跨会话的持久行为更改
- 团队共享配置
- 专门的助手(代码审查员、数据科学家、DevOps)
- 需要版本控制的复杂提示修改
示例:
- 创建专用的 SQL 优化助手
- 构建以安全为重点的代码审查员
- 开发具有特定教学法的教学助手
何时使用带 append 的 systemPrompt
最适合:
- 添加特定的编码标准或偏好
- 自定义输出格式
- 添加领域特定的知识
- 修改响应的详细程度
- 在不丢失工具说明的情况下增强 Claude Code 的默认行为
何时使用自定义 systemPrompt
最适合:
- 完全控制 Claude 的行为
- 专门的单会话任务
- 测试新的提示策略
- 不需要默认工具的情况
- 构建具有独特行为的专门代理
组合方法
你可以组合这些方法以获得最大的灵活性:
示例:具有会话特定补充的输出样式
TypeScript
import { query } from "@anthropic-ai/claude-agent-sdk";
// Assuming "Code Reviewer" output style is active (via /output-style)
// Add session-specific focus areas
const messages = [];
for await (const message of query({
prompt: "Review this authentication module",
options: {
systemPrompt: {
type: "preset",
preset: "claude_code",
append: `
For this review, prioritize:
- OAuth 2.0 compliance
- Token storage security
- Session management
`
}
}
})) {
messages.push(message);
}
Python
from claude_agent_sdk import query, ClaudeAgentOptions
# Assuming "Code Reviewer" output style is active (via /output-style)
# Add session-specific focus areas
messages = []
async for message in query(
prompt="Review this authentication module",
options=ClaudeAgentOptions(
system_prompt={
"type": "preset",
"preset": "claude_code",
"append": """
For this review, prioritize:
- OAuth 2.0 compliance
- Token storage security
- Session management
""",
}
),
):
messages.append(message)
另请参阅
- 输出样式 - 完整的输出样式文档
- TypeScript SDK 指南 - 完整的 SDK 使用指南
- 配置指南 - 一般配置选项
本文翻译自 Anthropic Claude Code 官方文档,最近一次同步:2025-05-01。