2026-05-20 21:39:12 +08:00

107 lines
3.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Prompt Builder 分层注入系统
created: 2026-04-16
updated: 2026-04-19
type: concept
tags: [agent, llm, architecture]
sources: [packages/backend/src/modules/netaclaw/runtime/prompt_builder.ts, packages/backend/src/modules/netaclaw/runtime/prompt_guidance.ts, packages/backend/src/modules/netaclaw/controller/agent.ts]
---
# Prompt Builder 分层注入系统
## 定义
8 层分层系统,将 Agent 的系统提示词从多个来源统一组装。它本身是纯函数层,但现在通常接收来自 [[tool-governance]] 的最终 `toolNames``toolPromptHints`,不再单独决定运行时工具可见性。
## 8 层结构
```text
Layer 1: Agent 身份agentSystemPrompt
Layer 2: 工具使用纪律(基于 availableToolNames 动态生成)
Layer 3: 模型特定指导GPT/DeepSeek/MiniMax/豆包/通义千问/GLM
Layer 4: 工具行为策略(基于工具列表 + Prompt Hint
Layer 5: Skill 索引(如果有 Skill
Layer 6: 记忆系统(如果启用记忆)
Layer 7: Crew 编排上下文(如果是 Crew 模式)
Layer 8: 元信息时间戳、模型ID
```
## 核心文件
| 文件 | 职责 |
|------|------|
| `runtime/prompt_builder.ts` | `buildSystemPrompt()` 主函数8层组装 |
| `runtime/prompt_guidance.ts` | 指导文本常量集中管理 |
| `controller/agent.ts` | 预览接口,展示最终 layers/toolNames/disabledReasons |
## 关键 API
```typescript
interface BuildSystemPromptParams {
agentSystemPrompt: string;
modelId: string;
availableToolNames: string[];
skills: string[];
skillLoader: SkillLoaderService;
memoryEnabled: boolean;
memoryContext?: string;
crewContext?: string;
toolPromptHints?: Record<string, string>;
}
buildSystemPrompt(params): { prompt: string, layers: PromptLayer[] }
```
## 关键变化
### 旧模式
Prompt Builder 可直接通过 `collectAvailableToolNames()` 结合 toolset 推导工具列表。
### 当前主路径
当前真正用于运行时和预览的主链路是:
```text
Agent 配置 + 全局 Tool 配置 + 模型能力 + 上下文角色
→ tool_resolver.resolve()
→ 输出 toolNames / toolPromptHints / disabledReasons
→ buildSystemPrompt()
```
因此 Prompt Builder 更像“最终提示词组装器”,而不是“工具决策器”。
## 模型特定指导
`getModelGuidance(modelId)` 会为不同模型生成约束性指导,用于减少工具调用和 schema 输出偏差。
## Prompt Hint
Layer 4 现在支持从 [[tool-governance]] 注入 `toolPromptHints`,用于覆写单个工具的行为指令。这个能力使运营侧可以不改工具代码就微调模型使用方式。
## 预览接口
Agent 编辑页通过:
```text
POST /admin/netaclaw/agent/previewPrompt
```
直接返回:
- `layers`
- `toolNames`
- `disabledReasons`
这让前端可以同时看到最终提示词和为什么某些工具没生效。
## 关联页面
- [[tool-catalog]] — schema 注册来源
- [[tool-governance]] — 最终工具列表与 Prompt Hint 来源
- [[agent-runtime]] — 调用 buildSystemPrompt 的执行引擎
- [[llm-providers]] — 模型特定指导的适配对象
- [[skill-system]] — Layer 5 Skill 索引来源
- [[memory-system]] — Layer 6 记忆上下文来源
- [[crew-orchestration]] — Layer 7 Crew 编排上下文来源