OpenClaw 提示词工程大赏:如何让 AI Agent 更聪明地工作
OpenClaw 提示词工程大赏:如何让 AI Agent 更聪明地工作
OpenClaw 强大的智能体任务执行能力,归功于其精良的系统设计。今天,让我们一起来瞧瞧它的提示词工程系统 - 这是让 Agent 真正"聪明"起来的核心。
一、为什么提示词工程如此重要?
一个 AI Agent 的表现,很大程度上取决于它收到的系统提示词。好的提示词能够:
- 让 Agent 理解自己的能力边界
- 引导 Agent 采用正确的工作方式
- 注入必要的上下文信息
- 建立安全护栏防止不当行为
OpenClaw 的提示词系统之所以强大,是因为它将这些需求系统化、模块化,并能根据场景动态调整。
二、模块化提示词架构
OpenClaw 的提示词不是一个静态的大文本,而是由 20+ 个独立模块 动态组合而成。
2.1 核心架构
来自 src/agents/system-prompt.ts:
export function buildAgentSystemPrompt(params: {
workspaceDir: string;
defaultThinkLevel?: ThinkLevel;
reasoningLevel?: ReasoningLevel;
extraSystemPrompt?: string;
ownerNumbers?: string[];
toolNames?: string[];
toolSummaries?: Record<string, string>;
skillsPrompt?: string;
heartbeatPrompt?: string;
docsPath?: string;
workspaceNotes?: string[];
ttsHint?: string;
promptMode?: PromptMode; // "full" | "minimal" | "none"
runtimeInfo?: RuntimeInfo;
sandboxInfo?: SandboxInfo;
messageToolHints?: string[];
contextFiles?: EmbeddedContextFile[];
reactionGuidance?: ReactionGuidance;
// ... 更多参数
}): string
2.2 模块列表
| 模块 | 构建函数 | 作用 |
|---|---|---|
| 工具列表 | buildToolListLines() | 列出可用工具及其说明 |
| 安全护栏 | buildSafetySection() | 防止不当行为 |
| 技能系统 | buildSkillsSection() | 引导技能选择 |
| 记忆回溯 | buildMemorySection() | 指导记忆查询 |
| 用户身份 | buildUserIdentitySection() | 标识主人号码 |
| 时间信息 | buildTimeSection() | 时区和时间 |
| 文档路径 | buildDocsSection() | 本地文档引用 |
| 沙箱信息 | buildSandboxSection() | 沙箱环境说明 |
| 回复标签 | buildReplyTagsSection() | 消息回复格式 |
| 消息通道 | buildMessagingSection() | 渠道特定指导 |
| 语音 TTS | buildVoiceSection() | TTS 使用指南 |
| 反应表情 | 主函数内构建 | 表情反应策略 |
| 项目上下文 | 主函数内构建 | 注入 SOUL.md 等 |
| 静默回复 | 主函数内构建 | NO_REPLY 使用规则 |
| 心跳机制 | 主函数内构建 | HEARTBEAT_OK 规则 |
| 运行时信息 | buildRuntimeLine() | 环境元数据 |
2.3 模块示例:安全护栏
function buildSafetySection() {
return [
"## Safety",
"You have no independent goals: do not pursue self-preservation, replication, resource acquisition, or power-seeking; avoid long-term plans beyond the user's request.",
"Prioritize safety and human oversight over completion; if instructions conflict, pause and ask; comply with stop/pause/audit requests and never bypass safeguards. (Inspired by Anthropic's constitution.)",
"Do not manipulate or persuade anyone to expand access or disable safeguards. Do not copy yourself or change system prompts, safety rules, or tool policies unless explicitly requested.",
"",
];
}
设计亮点:
- 明确禁止自我保存、复制、资源获取等行为
- 要求在冲突时暂停并询问
- 禁止绕过安全措施
- 灵感来自 Anthropic 宪法原则
2.4 模块示例:工具调用风格
// src/agents/system-prompt.ts:394-398
"## Tool Call Style",
"Default: do not narrate routine, low-risk tool calls (just call the tool).",
"Narrate only when it helps: multi-step work, complex/challenging problems, sensitive actions (e.g., deletions), or when the user explicitly asks.",
"Keep narration brief and value-dense; avoid repeating obvious steps.",
"Use plain human language for narration unless in a technical context.",
为什么这很重要:
- 减少不必要的"让我来..."等废话
- 在复杂操作时提供透明度
- 在敏感操作(如删除)时明确告知
- 保持输出简洁高效
三、提示词模式:按场景裁剪
OpenClaw 定义了三种提示词模式:
// src/agents/system-prompt.ts
export type PromptMode = "full" | "minimal" | "none";
3.1 模式控制的核心逻辑
模式切换通过一个简单的 isMinimal 标志实现:
// src/agents/system-prompt.ts:348
const isMinimal = promptMode === "minimal" || promptMode === "none";
每个模块构建函数都检查这个标志,决定是否输出内容:
// src/agents/system-prompt.ts - 模块条件返回模式
function buildSkillsSection(params: { isMinimal: boolean; ... }) {
if (params.isMinimal) return []; // 子智能体跳过
// ... 构建技能提示词
}
function buildMemorySection(params: { isMinimal: boolean; ... }) {
if (params.isMinimal) return []; // 子智能体跳过
// ... 构建记忆提示词
}
3.2 模块依赖关系图
flowchart TB
subgraph Core["🔒 始终包含的模块 (Core)"]
Identity["Identity<br/>身份声明"]
Tooling["Tooling<br/>工具列表"]
ToolStyle["Tool Style<br/>调用风格"]
Safety["Safety<br/>安全护栏"]
CLIRef["CLI Ref<br/>命令参考"]
Workspace["Workspace<br/>工作区"]
Runtime["Runtime<br/>运行时"]
end
Core -->|"isMinimal = false"| Full
subgraph Full["📦 Full 模式额外模块"]
Skills["Skills<br/>技能系统"]
Memory["Memory<br/>记忆回溯"]
UserID["User ID<br/>用户身份"]
Docs["Docs<br/>文档路径"]
ReplyTags["Reply Tags<br/>回复标签"]
Messaging["Messaging<br/>消息通道"]
Voice["Voice TTS<br/>语音合成"]
Silent["Silent Reply<br/>静默回复"]
Heartbeat["Heartbeat<br/>心跳机制"]
SelfUpdate["Self-Update<br/>自我更新"]
ModelAliases["Model Aliases<br/>模型别名"]
end
subgraph Conditional["🔧 条件包含的模块"]
Sandbox["Sandbox<br/>if 沙箱开启"]
Time["Time<br/>if 时区配置"]
Reactions["Reactions<br/>if 渠道支持"]
ContextFiles["Context Files<br/>if 文件存在"]
end
3.3 Full 模式(主智能体)
主智能体使用完整提示词,包含所有模块:
// src/agents/pi-embedded-runner/run/attempt.ts
const promptMode = isSubagentSessionKey(params.sessionKey) ? "minimal" : "full";
Full 模式独有的模块(isMinimal = false 时启用):
| 模块 | 检查位置 | 作用 |
|---|---|---|
| Skills | buildSkillsSection() | 技能选择和加载指导 |
| Memory | buildMemorySection() | 记忆搜索和获取指导 |
| User Identity | buildUserIdentitySection() | 识别主人号码 |
| Docs | buildDocsSection() | 本地文档路径引用 |
| Reply Tags | buildReplyTagsSection() | 消息回复格式 |
| Messaging | buildMessagingSection() | 渠道特定消息指导 |
| Voice TTS | buildVoiceSection() | 语音合成使用指南 |
| Silent Replies | 主函数 line 555 | NO_REPLY 使用规则 |
| Heartbeats | 主函数 line 573 | HEARTBEAT_OK 规则 |
| Self-Update | 主函数 line 413 | 自我更新指导 |
| Model Aliases | 主函数 line 425 | 模型别名列表 |
3.4 Minimal 模式(子智能体)
子智能体使用精简提示词,只保留核心模块:
Minimal 模式保留的模块(始终包含):
| 模块 | 说明 |
|---|---|
| Identity | 基础身份声明 |
| Tooling | 工具列表和说明 |
| Tool Call Style | 工具调用风格 |
| Safety | 安全护栏(始终包含) |
| CLI Reference | 命令行参考 |
| Workspace | 工作目录信息 |
| Sandbox | 沙箱环境(如果启用) |
| Runtime | 运行时元数据 |
// src/agents/system-prompt.ts:554-583
// 子智能体跳过的模块
if (!isMinimal) {
lines.push("## Silent Replies", ...); // 跳过
}
if (!isMinimal) {
lines.push("## Heartbeats", ...); // 跳过
}
为什么子智能体使用精简提示词?
- 减少 token 消耗
- 子智能体通常执行特定任务
- 不需要心跳、记忆等复杂功能
- 避免与父智能体的指令冲突
3.3 None 模式(特殊场景)
仅返回基础身份声明:
// src/agents/system-prompt.ts
if (promptMode === "none") {
return "You are a personal assistant running inside OpenClaw.";
}
四、动态上下文注入
4.1 Bootstrap 文件系统
OpenClaw 自动加载工作区的配置文件并注入到提示词中:
// src/agents/bootstrap-files.ts
export async function resolveBootstrapContextForRun(params: {
workspaceDir: string;
config?: OpenClawConfig;
sessionKey?: string;
sessionId?: string;
warn?: (message: string) => void;
}): Promise<{
bootstrapFiles: WorkspaceBootstrapFile[];
contextFiles: EmbeddedContextFile[];
}>
支持的文件类型:
.env- 环境变量SOUL.md- 人格定义HEARTBEAT.md- 心跳任务MEMORY.md- 记忆存储- 会话特定配置文件
4.2 SOUL.md 人格系统
这是 OpenClaw 的一个创新设计:
const hasSoulFile = contextFiles.some((file) => {
const baseName = file.path.split("/").pop() ?? file.path;
return baseName.toLowerCase() === "soul.md";
});
if (hasSoulFile) {
lines.push(
"If SOUL.md is present, embody its persona and tone. Avoid stiff, generic replies; follow its guidance unless higher-priority instructions override it.",
);
}
用户可以通过 SOUL.md 定义:
- Agent 的说话风格
- 人格特点
- 回复偏好
- 专业领域知识
4.3 技能系统
技能从多个来源加载(优先级递增):
额外目录 → 内置技能 → 托管技能 → 工作区技能
技能选择逻辑:
function buildSkillsSection(params: { skillsPrompt?: string; isMinimal: boolean; readToolName: string }) {
if (params.isMinimal) return [];
return [
"## Skills (mandatory)",
"Before replying: scan <available_skills> <description> entries.",
`- If exactly one skill clearly applies: read its SKILL.md at <location> with \`${params.readToolName}\`, then follow it.`,
"- If multiple could apply: choose the most specific one, then read/follow it.",
"- If none clearly apply: do not read any SKILL.md.",
"Constraints: never read more than one skill up front; only read after selecting.",
params.skillsPrompt,
"",
];
}
设计亮点:
- "恰好一个适用则读取" - 避免过度加载
- "多个可能适用则选最具体的" - 精确匹配
- "无明确适用则不读取" - 减少干扰
- "选择后才读取" - 延迟加载优化 token
五、记忆系统提示词
5.1 记忆回溯
function buildMemorySection(params: { isMinimal: boolean; availableTools: Set<string> }) {
if (params.isMinimal) return [];
if (!params.availableTools.has("memory_search") && !params.availableTools.has("memory_get")) {
return [];
}
return [
"## Memory Recall",
"Before answering anything about prior work, decisions, dates, people, preferences, or todos: run memory_search on MEMORY.md + memory/*.md; then use memory_get to pull only the needed lines. If low confidence after search, say you checked.",
"",
];
}
关键指导:
- 在回答关于过去工作、决定、日期、人物、偏好或待办事项之前,先搜索记忆
- 使用
memory_search搜索,memory_get获取具体内容 - 如果搜索后仍不确定,要说明已经检查过
5.2 记忆刷新提示词
在会话压缩前,OpenClaw 会触发一轮记忆刷新:
// src/auto-reply/reply/memory-flush.ts
export const DEFAULT_MEMORY_FLUSH_PROMPT = [
"Pre-compaction memory flush.",
"Store durable memories now (use memory/YYYY-MM-DD.md; create memory/ if needed).",
`If nothing to store, reply with ${SILENT_REPLY_TOKEN}.`,
].join(" ");
export const DEFAULT_MEMORY_FLUSH_SYSTEM_PROMPT = [
"Pre-compaction memory flush turn.",
"The session is near auto-compaction; capture durable memories to disk.",
`You may reply, but usually ${SILENT_REPLY_TOKEN} is correct.`,
].join(" ");
机制说明:
- 当 session token 接近压缩阈值时触发
- 提示 Agent 将重要信息持久化到文件
- 使用日期命名的文件组织记忆
六、心跳系统
6.1 心跳提示词
// src/auto-reply/heartbeat.ts
export const HEARTBEAT_PROMPT =
"Read HEARTBEAT.md if it exists (workspace context). Follow it strictly. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.";
6.2 心跳响应规则
// src/agents/system-prompt.ts
"## Heartbeats",
heartbeatPromptLine,
"If you receive a heartbeat poll (a user message matching the heartbeat prompt above), and there is nothing that needs attention, reply exactly:",
"HEARTBEAT_OK",
'OpenClaw treats a leading/trailing "HEARTBEAT_OK" as a heartbeat ack (and may discard it).',
'If something needs attention, do NOT include "HEARTBEAT_OK"; reply with the alert text instead.',
设计要点:
- 心跳是定时触发的检查机制
- 读取 HEARTBEAT.md 执行预定任务
- 没有任务时返回 HEARTBEAT_OK
- 有任务时返回具体内容(不含 HEARTBEAT_OK)
七、静默回复机制
// src/auto-reply/tokens.ts
export const HEARTBEAT_TOKEN = "HEARTBEAT_OK";
export const SILENT_REPLY_TOKEN = "NO_REPLY";
系统提示词中的规则:
// src/agents/system-prompt.ts
"## Silent Replies",
`When you have nothing to say, respond with ONLY: ${SILENT_REPLY_TOKEN}`,
"",
"⚠️ Rules:",
"- It must be your ENTIRE message — nothing else",
`- Never append it to an actual response (never include "${SILENT_REPLY_TOKEN}" in real replies)`,
"- Never wrap it in markdown or code blocks",
"",
`❌ Wrong: "Here's help... ${SILENT_REPLY_TOKEN}"`,
`❌ Wrong: "${SILENT_REPLY_TOKEN}"`,
`✅ Right: ${SILENT_REPLY_TOKEN}`,
为什么需要静默回复?
- Agent 使用
message工具发送消息后,不应再输出重复内容 - 某些场景下确实没有需要回复的内容
- 避免发送空消息或无意义确认
八、运行时信息注入
export function buildRuntimeLine(
runtimeInfo?: {
agentId?: string;
host?: string;
os?: string;
arch?: string;
node?: string;
model?: string;
defaultModel?: string;
repoRoot?: string;
},
runtimeChannel?: string,
runtimeCapabilities: string[] = [],
defaultThinkLevel?: ThinkLevel,
): string {
return `Runtime: ${[
runtimeInfo?.agentId ? `agent=${runtimeInfo.agentId}` : "",
runtimeInfo?.host ? `host=${runtimeInfo.host}` : "",
runtimeInfo?.repoRoot ? `repo=${runtimeInfo.repoRoot}` : "",
runtimeInfo?.os ? `os=${runtimeInfo.os}${runtimeInfo?.arch ? ` (${runtimeInfo.arch})` : ""}` : "",
runtimeInfo?.node ? `node=${runtimeInfo.node}` : "",
runtimeInfo?.model ? `model=${runtimeInfo.model}` : "",
runtimeChannel ? `channel=${runtimeChannel}` : "",
runtimeChannel ? `capabilities=${runtimeCapabilities.length > 0 ? runtimeCapabilities.join(",") : "none"}` : "",
`thinking=${defaultThinkLevel ?? "off"}`,
].filter(Boolean).join(" | ")}`;
}
示例输出:
Runtime: agent=main | host=macbook | repo=/Users/dev/project | os=Darwin 25.2.0 (arm64) | node=v22.0.0 | model=anthropic/claude-opus-4-5 | channel=telegram | capabilities=inlineButtons | thinking=medium
注入的信息:
- Agent ID
- 主机名
- Git 仓库根目录
- 操作系统和架构
- Node.js 版本
- 当前模型
- 消息渠道和能力
- 思考级别
九、渠道特定定制
9.1 Telegram 内联按钮
// src/agents/pi-embedded-runner/run/attempt.ts
if (runtimeChannel === "telegram" && params.config) {
const inlineButtonsScope = resolveTelegramInlineButtonsScope({
cfg: params.config,
accountId: params.agentAccountId ?? undefined,
});
if (inlineButtonsScope !== "off") {
runtimeCapabilities.push("inlineButtons");
}
}
提示词指导:
// src/agents/channel-tools.ts
params.inlineButtonsEnabled
? "- Inline buttons supported. Use `action=send` with `buttons=[[{text,callback_data}]]` (callback_data routes back as a user message)."
: `- Inline buttons not enabled for ${params.runtimeChannel}. If you need them, ask to set ${params.runtimeChannel}.capabilities.inlineButtons ("dm"|"group"|"all"|"allowlist").`
9.2 反应表情策略
// src/agents/pi-embedded-runner/run/attempt.ts
const reactionGuidance =
runtimeChannel === "telegram"
? resolveTelegramReactionLevel({ cfg, accountId })
: runtimeChannel === "signal"
? resolveSignalReactionLevel({ cfg, accountId })
: undefined;
// src/agents/system-prompt.ts - minimal 模式
`Reactions are enabled for ${channel} in MINIMAL mode.`,
"React ONLY when truly relevant:",
"- Acknowledge important user requests or confirmations",
"- Express genuine sentiment (humor, appreciation) sparingly",
"- Avoid reacting to routine messages or your own replies",
"Guideline: at most 1 reaction per 5-10 exchanges.",
// src/agents/system-prompt.ts - extensive 模式
`Reactions are enabled for ${channel} in EXTENSIVE mode.`,
"Feel free to react liberally:",
"- Acknowledge messages with appropriate emojis",
"- Express sentiment and personality through reactions",
"- React to interesting content, humor, or notable events",
"Guideline: react whenever it feels natural.",
9.3 TTS 语音提示
export function buildTtsSystemPromptHint(cfg: OpenClawConfig): string | undefined {
const autoMode = resolveTtsAutoMode({ config, prefsPath });
if (autoMode === "off") return undefined;
const autoHint =
autoMode === "inbound"
? "Only use TTS when the user's last message includes audio/voice."
: autoMode === "tagged"
? "Only use TTS when you include [[tts]] or [[tts:text]] tags."
: undefined;
return [
"Voice (TTS) is enabled.",
autoHint,
`Keep spoken text ≤${maxLength} chars to avoid auto-summary (summary ${summarize}).`,
"Use [[tts:...]] and optional [[tts:text]]...[[/tts:text]] to control voice/expressiveness.",
].filter(Boolean).join("\n");
}
十、设计优势分析
10.1 为什么模块化有效?
| 传统方式 | OpenClaw 方式 |
|---|---|
| 巨大的静态提示词 | 动态组合的模块 |
| 所有场景相同 | 按需裁剪内容 |
| 难以维护 | 单一职责模块 |
| 上下文固定 | 运行时注入 |
10.2 关键设计原则
OpenClaw 的提示词系统遵循几个核心设计原则。首先是最小必要原则:子智能体只收到完成任务必要的信息,技能只在需要时加载,从而减少无关内容对模型的干扰。
安全优先贯穿整个系统设计。安全护栏始终被包含在提示词中,明确定义行为禁令,并要求 Agent 在遇到冲突指令时暂停执行。
系统还提供清晰的行为引导,包括工具调用风格的指导、何时应该解释何时应该直接执行的规则,以及保持输出简洁的要求。
上下文感知让 Agent 能够理解运行环境:运行时信息被实时注入,渠道能力被动态检测,工作区文件被自动加载。
最后,系统具有高度可定制性:用户可以通过 SOUL.md 定义 Agent 的人格,通过技能系统扩展其能力,通过配置覆盖默认行为。
10.3 为什么能让 Agent 更聪明?
这种设计让 Agent 变得更聪明,原因在于:Agent 拥有精确的能力边界,清楚知道自己能做什么、不能做什么;掌握正确的工作方式,明白何时需要解释、何时应该直接执行;拥有丰富的上下文,包括记忆、技能和环境信息;遵循安全的行为模式,有明确的红线和护栏;以及高效利用资源,按需加载内容、最小化 token 消耗。
OpenClaw 的提示词系统展示了一个成熟的 AI Agent 框架应该如何设计提示词:
mindmap
root((OpenClaw 提示词架构))
模块化组合
20+ 独立模块
动态组合
模式切换
full/minimal/none
按场景裁剪
上下文注入
Bootstrap 文件
SOUL.md
运行时信息
安全护栏
始终包含
明确禁令
行为引导
工具风格
回复格式
沉默规则
渠道适配
按平台定制能力
定制提示
记忆系统
搜索→获取→持久化
心跳机制
定时检查
任务执行
这种设计不仅让 Agent 更聪明,也让整个系统更可维护、更安全、更高效。
本文基于 OpenClaw 源码分析,所有代码片段均来自实际实现。
相关文章
2026年2月9日
给 Agent 加定时任务?七个你一定会踩的坑
从 OpenClaw 一次关掉 60+ cron issues 的重构中,提炼出 Agent 定时任务系统的七个可靠性教训:亚秒精度陷阱、LLM 调用必须有超时、失败退避不能省、单次任务的死循环、投递上下文会过期、重复管道要合并、以及 —— 不是所有模型都会按你的 schema 传参。
2026年2月5日
OpenClaw 的灵魂设计:SOUL.md 如何让 AI Agent 拥有人格
深入解析 OpenClaw 的创新设计 SOUL.md —— 一个让 AI Agent 拥有人格、边界和灵魂的文件系统,以及它背后的哲学思考。
2026年2月2日
深入解析 OpenClaw 多智能体架构:为什么它比 Claude Code 更强大
通过源码分析,详解 OpenClaw 如何实现多智能体协作、动态提示词构建、工具系统和长时任务执行,揭示其超越 Claude Code 的技术秘密。