第 5 章:系统提示词(System Prompt)装配
1. 本章定位
系统提示词不是一个常量,而是插件按作用域贡献并在每次调用前装配的结构。
2. 学习目标
- 区分
section、context、tools、variable。 - 解释注册顺序、作用域和 complete section。
- 从
assemble()追到renderPrompt()。 - 识别提示词顺序对模型缓存和行为的影响。
3. 前置知识
可把贡献项类比为命名 Slot,把本次 Scope 类比为组件 render 的 props。局限是输出顺序会影响模型约束与 KV Cache,不能把 section 当任意 UI 子树重排。
4. 对应源码
packages/core/system-prompt/src/index.ts:263:renderPrompt()。packages/core/system-prompt/src/index.ts:302:context 渲染。packages/core/system-prompt/src/index.ts:389:SystemPrompt。packages/core/system-prompt/src/index.ts:432:section()。packages/core/system-prompt/src/index.ts:467:context()。packages/core/system-prompt/src/index.ts:499:tools()。packages/core/system-prompt/src/index.ts:515:variable()。packages/core/system-prompt/src/index.ts:536:assemble()。
5. 工作原理
插件注册四类贡献;装配时读取当前 Scope,解析 shadow/complete 语义与顺序,经 system-prompt/assemble waterfall 允许扩展,最后严格替换变量并生成本次模型请求的 system 文本和工具说明。
6. 执行流程
无图回退:section/context/tools/variable → 当前 Prompt Scope → SystemPrompt.assemble() → waterfall → renderPrompt() → PreparedLlmCall。
7. 关键源码讲解
section() 和 context() 解决内容贡献,tools() 保证模型看到的能力说明与当前作用域一致,variable() 延迟提供运行时值。assemble() 的顺序是行为;动态内容插入稳定前缀前会降低 provider 缓存复用。waterfall 若直接替换结果,必须保留其他插件的贡献。
8. 调试与观察方法
在 assemble() 返回处查看贡献来源、顺序和 Scope;在 renderPrompt() 未知变量分支设置异常断点。工具执行存在但 Schema 不可见时,先比较 Prompt 的工具集合与 ToolRuntime restriction。
9. 本章实践任务
注册一个 study:note section 和变量,断言全局/局部 Scope、顺序、未知变量错误和卸载恢复。验收:测试不是只查字符串包含,还验证顺序与 Disposer。
10. 常见误区
- 把 persona 当唯一提示词来源。
- 在 waterfall 中丢掉已有贡献。
- 把高频动态内容放到稳定前缀前。
11. 自测题
- 四类贡献分别解决什么问题?
- complete section 有什么边界?
- 未注册变量如何失败?
- 顺序为何影响 KV Cache?
- scoped shadow 比修改全局贡献安全在哪里?