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