这一节只讲相对 S09 新增的内容:
System Prompt 不再写死,而是根据真实运行状态动态组装,并做缓存。
PROMPT_SECTIONS:提示词片段字典。assemble_system_prompt(context):根据上下文拼接提示词。get_system_prompt(context):带缓存的提示词获取函数。update_context(context, messages):从当前项目状态推导上下文。agent_loop(messages, context):循环里使用动态 system prompt。PROMPT_SECTIONSPROMPT_SECTIONS 是一个字典:
PROMPT_SECTIONS: dict[str, str] = {
"identity": "你是一个编码 Agent。直接行动,不要只解释。"
}
它把 System Prompt 拆成多个可组合片段。
后面可以根据实际状态决定加载哪些片段。
context 数据结构context 是运行时上下文:
context: dict = {
"enabled_tools": ["bash", "read_file", "write_file"],
"workspace": "/path/to/project",
"memories": "- [user-style](user-style.md) — 用户偏好..."
}
它不是模型消息,而是程序用来组装 System Prompt 的状态。
assemble_system_prompt(context)作用:根据 context 生成最终 System Prompt。
流程:
加入身份片段
加入当前可用工具
加入工作目录
如果有记忆索引,就加入记忆
最后用空行拼接
输出是字符串:
system: str
然后传给:
client.messages.create(system=system, ...)
get_system_prompt(context)作用:如果上下文没变,就复用上一次组装好的提示词。
关键变量:
_last_context_key: str | None
_last_prompt: str | None
它先把 context 转成稳定字符串:
key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)
如果 key 没变:
return _last_prompt
如果变了:
_last_prompt = assemble_system_prompt(context)
update_context(context, messages)作用:从真实状态生成新的上下文。
这一节主要读取:
.memory/MEMORY.md
如果存在记忆索引,就放进:
context["memories"]
同时把当前工具列表和工作目录放进去。
System Prompt 不应该是一大坨永远不变的字符串。
更工程化的方式是:
基础身份固定
工具列表来自真实注册表
工作目录来自真实环境
记忆来自真实文件
上下文变化后再重新组装
这就是动态提示词系统。