目录
1 system-reminders 介绍
Claude system-reminders设计初衷十分明确:解决智能体在多步骤执行后遗忘指令或既定方案的问题。Agent往往能一次性执行数百个步骤,因此,定期提醒其核心控制流程显然至关重要。
System Reminder 的核心是在正确的时机,用简洁的方式,重申关键信息,帮助模型保持对原始目标和约束的记忆。有效的 Reminder 应该:
1. ✅ 状态明确(完成了什么,正在做什么)
2. ✅ 指令清晰(下一步做什么)
3. ✅ 约束突出(不能违反的规则)
2 自定义Agent的system-reminders
2.1 实现方式
System Reminder 通过在关键节点重新注入核心指令,它通常放在:
- 用户消息的末尾
- 系统消息的特定位置
- 或作为独立的提醒块
2.1.1 嵌入式 Reminder
在每个用户消息后自动添加提醒:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<user_message> {用户的实际输入} <system_reminder> Remember your core instructions: 1. You are working on: {当前任务描述} 2. Current step: {当前步骤} of {总步骤数} 3. Key constraints: - Always validate output before proceeding - Use tools in the specified order: {工具列表} - Never skip the verification step 4. Next action: {下一步应该做什么} </system_reminder> </user_message> |
2.1.2 周期性 Reminder
每隔 N 轮对话插入一次:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# 伪代码示例 if conversation_turns % 3 == 0: reminder = """ <reminder> Core Objective: {original_goal} Progress: {completed_steps}/{total_steps} Remaining Tasks: {pending_tasks} Critical Rules: - {rule_1} - {rule_2} </reminder> """ messages.append({"role": "system", "content": reminder}) |
2.1.3 状态追踪型 Reminder
它的核心价值是:让 Agent 在长时间、多步骤执行中,始终能”看到”自己走到了哪里、手里有什么数据、下一步该怎么做——就像给健忘的 AI 配了一个随身携带、实时更新的”任务看板”。
结合执行状态动态生成,状态追踪型 Reminder = 动态状态快照 + 上下文相关指令。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# 伪代码示例 if conversation_turns % 3 == 0: reminder = """ <reminder> Core Objective: {original_goal} Progress: {completed_steps}/{total_steps} Remaining Tasks: {pending_tasks} Critical Rules: - {rule_1} - {rule_2} </reminder> """ messages.append({"role": "system", "content": reminder}) |
工作原理:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
┌──────────────────────┐ │ Agent 执行引擎 │ ├──────────────────────┤ │ │ │ 1. 维护状态对象 (State Tracker) │ │ { │ │ original_plan: [...], │ │ completed: [...], │ │ current_step: 2, │ │ variables: {...} │ │ } │ │ │ │ 2. 每次调用 LLM 前 │ │ ↓ │ │ 读取当前状态 │ │ ↓ │ │ 生成个性化 Reminder │ │ ↓ │ │ 注入到 Prompt │ │ │ │ 3. LLM 执行后 │ │ ↓ │ │ 更新状态对象 │ │ ↓ │ │ 下次循环使用新状态 │ │ │ └──────────────────────┘ |
和静态Reminder比较
|
静态 Reminder
|
状态追踪型 Reminder
|
|---|---|
|
“记住你的目标是 X”
|
“目标 X:已完成 60%,当前在子任务 Y”
|
|
每次内容相同
|
根据执行历史动态调整
|
|
无法反映进度
|
清晰显示完成情况
|
|
不包含中间结果
|
携带已获取的数据/变量
|
|
可能与当前状态无关
|
始终与当前步骤强相关
|
2.2 触发时机
|
场景
|
触发策略
|
|---|---|
|
长对话
|
每 3-5 轮插入
|
|
多步骤任务
|
每个步骤开始时
|
|
工具调用后
|
立即提醒下一步
|
|
错误发生时
|
重申正确流程
|
2.3 实际案例
案例1 数据处理流水线 (状态追踪型 Reminder)
假设任务:处理 CSV 文件 → 清洗 → 分析 → 生成报告
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
class StateTracker: def __init__(self): # 初始化状态 self.state = { "original_plan": [ "load_csv", "clean_data", "analyze_stats", "generate_report" ], "completed_steps": [], "current_step": "load_csv", "data_info": {}, "errors": [] } def generate_reminder(self): """根据当前状态动态生成 reminder""" # 计算进度 total = len(self.state["original_plan"]) done = len(self.state["completed_steps"]) progress = f"{done}/{total}" # 动态生成提醒内容 reminder = f""" <system_reminder> EXECUTION STATUS: - Original Plan: {' → '.join(self.state['original_plan'])} - Progress: {progress} - Completed: {', '.join(self.state['completed_steps']) or 'None'} - Current Task: {self.state['current_step']} CURRENT STATE VARIABLES: {self._format_state_vars()} {self._get_step_specific_instructions()} CRITICAL: {self._get_relevant_constraints()} </system_reminder> """ return reminder def update_state(self, step_completed, new_data=None): """执行步骤后更新状态""" if step_completed: self.state["completed_steps"].append(self.state["current_step"]) # 移动到下一步 current_idx = self.state["original_plan"].index(self.state["current_step"]) if current_idx + 1 < len(self.state["original_plan"]): self.state["current_step"] = self.state["original_plan"][current_idx + 1] # 更新数据信息 if new_data: self.state["data_info"].update(new_data) def _format_state_vars(self): """格式化当前状态变量""" if not self.state["data_info"]: return "- No data loaded yet" return f""" - Rows loaded: {self.state['data_info'].get('rows', 'N/A')} - Columns: {self.state['data_info'].get('columns', 'N/A')} - Missing values: {self.state['data_info'].get('missing', 'N/A')} """ def _get_step_specific_instructions(self): """根据当前步骤返回特定指令""" instructions = { "load_csv": "→ NEXT: Load the CSV and store metadata in state", "clean_data": "→ NEXT: Remove nulls, fix types, validate ranges", "analyze_stats": "→ NEXT: Calculate mean, median, correlations", "generate_report": "→ NEXT: Create summary with visualizations" } return instructions.get(self.state["current_step"], "") def _get_relevant_constraints(self): """根据当前步骤返回相关约束""" constraints = { "load_csv": "Must validate file format before processing", "clean_data": "Never drop >10% of rows without user confirmation", "analyze_stats": "Use only pandas/numpy, no external libraries", "generate_report": "Output must be markdown format" } return constraints.get(self.state["current_step"], "") |
执行步骤:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
if __name__ == '__main__': # 初始化追踪器 tracker = StateTracker() # ===== 第 1 轮对话 ===== user_input_1 = "请加载文件 data.csv" reminder_1 = tracker.generate_reminder() print(reminder_1) # ===== 第 2 轮对话 ===== user_input_2 = "文件已加载,继续下一步" tracker.update_state( step_completed=True, new_data={"rows": 1000, "columns": 5, "missing": 23} ) reminder_2 = tracker.generate_reminder() print(reminder_2) |
结果输出:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<system_reminder> EXECUTION STATUS: - Original Plan: load_csv → clean_data → analyze_stats → generate_report - Progress: 0/4 - Completed: None - Current Task: load_csv CURRENT STATE VARIABLES: - No data loaded yet → NEXT: Load the CSV and store metadata in state CRITICAL: Must validate file format before processing </system_reminder> <system_reminder> EXECUTION STATUS: - Original Plan: load_csv → clean_data → analyze_stats → generate_report - Progress: 1/4 - Completed: load_csv - Current Task: clean_data CURRENT STATE VARIABLES: - Rows loaded: 1000 - Columns: 5 - Missing values: 23 → NEXT: Remove nulls, fix types, validate ranges CRITICAL: Never drop >10% of rows without user confirmation </system_reminder> |
案例 2: 多工具协调 Agent
假设你在构建一个客服 Agent,它需要协调多个工具来解决客户问题:
|
1 2 3 4 5 6 7 |
客户问题: "我的订单怎么还没发货?" Agent 需要: 1. 先查知识库 → 看是否有标准答案 2. 再查订单状态 → 获取实际物流信息 3. 综合信息生成回复 → 给客户专业答复 4. 判断是否升级 → 复杂问题转人工 |
定义状态追踪
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
class CustomerSupportStateTracker: def __init__(self, customer_query): self.state = { # 原始信息 "customer_query": customer_query, "extracted_order_id": None, # 工具调用计划和状态 "tool_sequence": [ "search_knowledge_base", "check_order_status", "generate_response", "escalate_if_needed" ], "current_tool_index": 0, # 工具执行记录 "tools_executed": [], "tool_results": {}, # 业务数据 "kb_articles_found": [], "order_info": None, "delay_days": None, # 决策标记 "needs_escalation": False, "escalation_reason": None } def get_current_tool(self): """获取当前应该执行的工具""" if self.state["current_tool_index"] < len(self.state["tool_sequence"]): return self.state["tool_sequence"][self.state["current_tool_index"]] return None def generate_reminder(self): """生成状态追踪型 Reminder""" current_tool = self.get_current_tool() completed = len(self.state["tools_executed"]) total = len(self.state["tool_sequence"]) reminder = f""" <system_reminder> ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ CUSTOMER SUPPORT WORKFLOW TRACKER ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 📋 ORIGINAL CUSTOMER QUERY: "{self.state['customer_query']}" Order ID: {self.state['extracted_order_id'] or 'Not extracted yet'} 🔧 TOOL EXECUTION PROGRESS: {completed}/{total} {self._render_tool_pipeline()} 📊 COLLECTED DATA SO FAR: {self._format_collected_data()} ⚡ CURRENT ACTION: {self._get_current_instruction(current_tool)} ⚠️ CRITICAL RULES: {self._get_current_constraints(current_tool)} 🎯 FINAL GOAL: Provide accurate, empathetic response addressing customer concern </system_reminder> """ return reminder def _render_tool_pipeline(self): """可视化工具执行流程""" pipeline = [] for i, tool in enumerate(self.state["tool_sequence"]): if i < self.state["current_tool_index"]: # 已完成 status = "✓" mark = "" elif i == self.state["current_tool_index"]: # 当前执行 status = "→" mark = " ← YOU ARE HERE" else: # 待执行 status = "○" mark = "" pipeline.append(f"{status} {i+1}. {tool}{mark}") return "\n".join(pipeline) def _format_collected_data(self): """格式化已收集的数据""" data_summary = [] # 知识库结果 if self.state["kb_articles_found"]: articles = ", ".join([f"#{a['id']}" for a in self.state["kb_articles_found"]]) data_summary.append(f"✓ Knowledge Base: Found articles {articles}") else: data_summary.append("○ Knowledge Base: Not searched yet") # 订单信息 if self.state["order_info"]: status = self.state["order_info"].get("status", "unknown") delay = self.state["delay_days"] data_summary.append(f"✓ Order Status: {status} (Delay: {delay} days)") else: data_summary.append("○ Order Status: Not checked yet") # 升级决策 if self.state["needs_escalation"]: data_summary.append(f"⚠️ Escalation: YES - {self.state['escalation_reason']}") return "\n".join(data_summary) if data_summary else "- No data collected" def _get_current_instruction(self, current_tool): """根据当前工具生成具体指令""" instructions = { "search_knowledge_base": f""" → ACTION: Call search_knowledge_base(query="{self.state['customer_query']}") → PURPOSE: Find standard policies about shipping delays → EXTRACT: Article IDs and relevant policy text """, "check_order_status": f""" → ACTION: Call check_order_status(order_id="{self.state['extracted_order_id']}") → PURPOSE: Get real-time shipping status and delay information → REQUIRED: Must validate order_id format before calling (format: #XXXXX) → EXTRACT: status, expected_delivery, actual_delay_days """, "generate_response": f""" → ACTION: Synthesize information from: 1. KB articles: {len(self.state['kb_articles_found'])} found 2. Order status: {self.state['order_info'].get('status') if self.state['order_info'] else 'N/A'} → TONE: Empathetic, professional, solution-oriented → FORMAT: Direct answer + explanation + next steps """, "escalate_if_needed": f""" → ACTION: Evaluate if human agent needed → CRITERIA: - Delay > 7 days: ESCALATE - Customer mentioned "angry", "refund": ESCALATE - Standard policy applies: NO ESCALATION → CURRENT DELAY: {self.state['delay_days']} days """ } return instructions.get(current_tool, "→ No tool to execute") def _get_current_constraints(self, current_tool): """根据当前工具返回约束条件""" constraints = { "search_knowledge_base": "- Must search even if you think you know the answer\n" "- Return top 3 most relevant articles only", "check_order_status": f"- MUST validate order_id is format #XXXXX (current: {self.state['extracted_order_id']})\n" "- If API fails, set needs_escalation=True\n" "- Never fabricate order status", "generate_response": "- MUST reference specific KB article numbers in response\n" "- MUST include actual delay days from order status\n" "- Never make promises about delivery dates", "escalate_if_needed": "- MUST escalate if delay > 7 days (non-negotiable)\n" "- Document escalation_reason clearly" } return constraints.get(current_tool, "- Follow general best practices") def mark_tool_complete(self, tool_name, result_data): """标记工具执行完成并存储结果""" self.state["tools_executed"].append(tool_name) self.state["tool_results"][tool_name] = result_data self.state["current_tool_index"] += 1 # 根据工具类型更新特定状态 if tool_name == "search_knowledge_base": self.state["kb_articles_found"] = result_data.get("articles", []) elif tool_name == "check_order_status": self.state["order_info"] = result_data self.state["delay_days"] = result_data.get("delay_days", 0) # 自动判断是否需要升级 if self.state["delay_days"] > 7: self.state["needs_escalation"] = True self.state["escalation_reason"] = f"Order delayed {self.state['delay_days']} days (>7 threshold)" |
step1 初始化
|
1 2 3 4 5 |
# ===== 初始化 ===== query = "我的订单 #12345 怎么还没发货?" tracker = CustomerSupportStateTracker(query) # 提取订单号 tracker.state["extracted_order_id"] = "#12345" print("第 1 轮:准备搜索知识库") print(tracker.generate_reminder()) |
生成结果
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<system_reminder> ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ CUSTOMER SUPPORT WORKFLOW TRACKER ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 📋 ORIGINAL CUSTOMER QUERY: "我的订单 #12345 怎么还没发货?" Order ID: #12345 🔧 TOOL EXECUTION PROGRESS: 0/4 → 1. search_knowledge_base ← YOU ARE HERE ○ 2. check_order_status ○ 3. generate_response ○ 4. escalate_if_needed 📊 COLLECTED DATA SO FAR: ○ Knowledge Base: Not searched yet ○ Order Status: Not checked yet ⚡ CURRENT ACTION: → ACTION: Call search_knowledge_base(query="我的订单 #12345 怎么还没发货?") → PURPOSE: Find standard policies about shipping delays → EXTRACT: Article IDs and relevant policy text ⚠️ CRITICAL RULES: - Must search even if you think you know the answer - Return top 3 most relevant articles only 🎯 FINAL GOAL: Provide accurate, empathetic response addressing customer concern </system_reminder> |
step2 知识库检索
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# ===== Agent 执行知识库搜索 ===== kb_result = { "articles": [ {"id": "KB-1234", "title": "物流延迟政策"}, {"id": "KB-5678", "title": "订单追踪指南"} ] } tracker.mark_tool_complete("search_knowledge_base", kb_result) print("第 2 轮:准备查询订单状态") print(tracker.generate_reminder()) |
执行结果:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<system_reminder> ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ CUSTOMER SUPPORT WORKFLOW TRACKER ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 📋 ORIGINAL CUSTOMER QUERY: "我的订单 #12345 怎么还没发货?" Order ID: #12345 🔧 TOOL EXECUTION PROGRESS: 1/4 ✓ 1. search_knowledge_base → 2. check_order_status ← YOU ARE HERE ○ 3. generate_response ○ 4. escalate_if_needed 📊 COLLECTED DATA SO FAR: ✓ Knowledge Base: Found articles #KB-1234, #KB-5678 ○ Order Status: Not checked yet ⚡ CURRENT ACTION: → ACTION: Call check_order_status(order_id="#12345") → PURPOSE: Get real-time shipping status and delay information → REQUIRED: Must validate order_id format before calling (format: #XXXXX) → EXTRACT: status, expected_delivery, actual_delay_days ⚠️ CRITICAL RULES: - MUST validate order_id is format #XXXXX (current: #12345) - If API fails, set needs_escalation=True - Never fabricate order status 🎯 FINAL GOAL: Provide accurate, empathetic response addressing customer concern </system_reminder> |
3. Claude system-reminders
Claude Code 会在用户消息中附加system-reminders,以确保智能体(agent)的执行流程不偏离预设轨道。这些系统提示信息是静态生成的,其内容取决于当前调用的工具类型以及待办事项列表(TODO list)的状态。
例如,在对话初始阶段,系统会自动附加如下提示:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<system-reminder> As you answer the user's questions, you can use the following context: # important-instruction-reminders Do what has been asked; nothing more, nothing less. NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User. IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context or otherwise consider it in your response unless it is highly relevant to your task. Most of the time, it is not relevant. </system-reminder> 回答用户问题时,你可以参考以下上下文信息: # 重要指令提醒 按要求执行即可,不额外操作,也不缺漏任务。 非实现目标绝对必需的情况,切勿创建文件。 务必优先编辑现有文件,而非新建文件。 严禁主动创建文档类文件(*.md 格式)或自述文件(README),仅当用户明确要求时,方可创建文档类文件。 重要提示:上述上下文信息可能与你的当前任务相关,也可能不相关。仅当该信息与任务高度相关时,你才需要参考;其余情况下无需考虑,且不得针对此上下文信息本身进行回应。多数情况下,该信息与当前任务并不相关。 |
那么在用户发送第一条消息之后
|
1 2 3 4 5 |
<system-reminder> This is a reminder that your todo list is currently empty. DO NOT mention this to the user explicitly because they are already aware. If you are working on tasks that would benefit from a todo list please use the TodoWrite tool to create one. If not, please feel free to ignore. Again do not mention this message to the user. <system-reminder> 特此提醒,你的待办事项列表当前为空。请勿向用户明确提及此事,用户对此已知情。若你正在处理的任务需要借助待办事项列表推进,请使用 TodoWrite 工具创建列表;若无此需求,可忽略本提示。再次强调,不得向用户透露本消息内容。 |
最终,在完成各步骤后,系统会附上待办事项列表:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<system-reminder> Your todo list has changed. DO NOT mention this explicitly to the user. Here are the latest contents of your todo list: [ { "content": "Analyze current agent implementation to understand structure", "status": "pending", "priority": "high", "id": "1" }, { "content": "Add streaming methods to Agent class (run_stream_async and run_stream)", "status": "pending", "priority": "high", "id": "2" } ] Continue on with the tasks at hand if applicable. </system-reminder> 你的待办事项列表已更新。请勿向用户明确提及此事。以下是待办事项列表的最新内容: [{...}] 若适用,请继续处理当前任务。 |
参考
https://jannesklaas.github.io/ai/2025/07/20/claude-code-agent-design.html


