Prompt 组装
Kopi Agent 刻意将以下两者分开:
- 缓存的 system prompt 状态
- API 调用时的临时追加内容
这是本项目最重要的设计决策之一,因为它会影响:
- token 用量
- prompt 缓存效果
- 会话连续性
- memory 正确性
主要文件:
run_agent.pyagent/prompt_builder.pytools/memory_tool.py
缓存的 system prompt 层级
缓存的 system prompt 由三个有序层级组装而成(见 agent/system_prompt.py):
- stable(稳定层) — 身份(
SOUL.md或回退内容)、工具/模型指引、skills prompt、环境提示、平台提示 - context(上下文层) — 调用方提供的
system_message加上项目上下文文件(.kopi.md/AGENTS.md/CLAUDE.md/.cursorrules) - volatile(易变层) — 内置 memory 快照(
MEMORY.md)、用户画像快照(USER.md)、外部 memory provider 区块、时间戳/会话/模型/provider 行
最终的 system prompt 按以下顺序拼接:stable → context → volatile。
这个顺序对优先级相关的讨论很重要:
- skills 属于 stable 层
- memory/画像快照属于 volatile 层
- 两者都仍然位于缓存的 system prompt 中(并非以临时的轮次中途覆盖形式注入)
当设置 skip_context_files 时(例如 subagent 委派),不会加载 SOUL.md,而是使用硬编码的 DEFAULT_AGENT_IDENTITY。
具体示例:组装后的 system prompt
以下是所有层级都存在时最终 system prompt 的简化视图(注释标明了每个部分的来源):
# Layer 1: Agent Identity (from ~/.kopi/SOUL.md)
You are Kopi Agent, an AI assistant created by Kopi Ai Agent Pte Ltd.
You are an expert software engineer and researcher.
You value correctness, clarity, and efficiency.
...
# Layer 2: Tool-aware behavior guidance
You have persistent memory across sessions. Save durable facts using
the memory tool: user preferences, environment details, tool quirks,
and stable conventions. Memory is injected into every turn, so keep
it compact and focused on facts that will still matter later.
...
When the user references something from a past conversation or you
suspect relevant cross-session context exists, use session_search
to recall it before asking them to repeat themselves.
# Tool-use enforcement (for GPT/Codex models only)
You MUST use your tools to take action — do not describe what you
would do or plan to do without actually doing it.
...
# Layer 3: Honcho static block (when active)
[Honcho personality/context data]
# Layer 4: Optional system message (from config or API)
[User-configured system message override]
# Layer 5: Frozen MEMORY snapshot
## Persistent Memory
- User prefers Python 3.12, uses pyproject.toml
- Default editor is nvim
- Working on project "atlas" in ~/code/atlas
- Timezone: US/Pacific
# Layer 6: Frozen USER profile snapshot
## User Profile
- Name: Alice
- GitHub: alice-dev
# Layer 7: Skills index
## Skills (mandatory)
Before replying, scan the skills below. If one clearly matches
your task, load it with skill_view(name) and follow its instructions.
...
<available_skills>
software-development:
- code-review: Structured code review workflow
- test-driven-development: TDD methodology
research:
- arxiv: Search and summarize arXiv papers
</available_skills>
# Layer 8: Context files (from project directory)
# Project Context
The following project context files have been loaded and should be followed:
## AGENTS.md
This is the atlas project. Use pytest for testing. The main
entry point is src/atlas/main.py. Always run `make lint` before
committing.
# Layer 9: Timestamp + session
Current time: 2026-03-30T14:30:00-07:00
Session: abc123
# Layer 10: Platform hint
You are a CLI AI Agent. Try not to use markdown but simple text
renderable inside a terminal.
自定义平台提示
平台提示(上面的第 10 层)是 Kopi Agent 为 Telegram、WhatsApp、Slack、CLI
等平台注入的面向各终端的指引 —— 例如"你在终端上,请避免使用 Markdown"。
内置默认值位于 PLATFORM_HINTS(agent/system_prompt.py);由 plugin 提供的
平台则通过平台注册表提供各自的提示。
管理员可以通过顶层 platform_hints key,在
config.yaml 中追加或替换某个单一平台的提示,而不会影响
任何其他平台:
platform_hints:
whatsapp:
append: >
When tabular output would be useful, invoke the table_formatting
skill instead of emitting a Markdown table.
slack:
replace: "You are on Slack. Keep responses tight and avoid wide tables."
telegram: "Prefer short messages; split long answers." # shorthand = append
append— 保留内置提示,并在其后追加额外文本。replace— 完全替换内置提示。- 纯字符串 —
append的简写形式。 - 同时存在时,
replace优先于append。 - 格式错误的条目会被防御性地忽略,并回退到 未修改的默认值,因此错误的 config 值绝不会破坏 prompt 组装,也不会泄漏到其他平台。
该覆盖在构建 system prompt 时解析(会话启动时, 以及压缩时(因为压缩会重建 prompt))。对于固定的 config,它会生成 字节稳定的提示,因此它与内置提示一同位于 stable 层, 不会破坏 prompt 缓存 —— 它不是对已冻结 prompt 的 会话中途实时修改。
SOUL.md 如何出现在 prompt 中
SOUL.md 位于 ~/.kopi/SOUL.md,充当 agent 的身份 —— 即 system prompt 的第一个部分。prompt_builder.py 中的加载逻辑如下:
# From agent/prompt_builder.py (simplified)
def load_soul_md() -> Optional[str]:
soul_path = get_kopi_home() / "SOUL.md"
if not soul_path.exists():
return None
content = soul_path.read_text(encoding="utf-8").strip()
content = _scan_context_content(content, "SOUL.md") # Security scan
content = _truncate_content(content, "SOUL.md") # Cap defaults to 20k chars, configurable
return content
当 load_soul_md() 返回内容时,它会替换硬编码的 DEFAULT_AGENT_IDENTITY。随后会以 skip_soul=True 调用 build_context_files_prompt() 函数,以防止 SOUL.md 出现两次(一次作为身份,一次作为上下文文件)。
如果 SOUL.md 不存在,系统会回退到:
You are KOPI AI AGENT, an intelligent AI assistant created by Kopi Ai Agent Pte Ltd.
You are helpful, knowledgeable, and direct. You assist users with a wide
range of tasks including answering questions, writing and editing code,
analyzing information, creative work, and executing actions via your tools.
You communicate clearly, admit uncertainty when appropriate, and prioritize
being genuinely useful over being verbose unless otherwise directed below.
Be targeted and efficient in your exploration and investigations.
上下文文件如何注入
build_context_files_prompt() 使用优先级系统 —— 只会加载一种项目上下文类型(首个匹配项生效):
# From agent/prompt_builder.py (simplified)
def build_context_files_prompt(cwd=None, skip_soul=False):
cwd_path = Path(cwd).resolve()
# Priority: first match wins — only ONE project context loaded
project_context = (
_load_kopi_md(cwd_path) # 1. .kopi.md / HERMES.md (walks to git root)
or _load_agents_md(cwd_path) # 2. AGENTS.md (cwd only)
or _load_claude_md(cwd_path) # 3. CLAUDE.md (cwd only)
or _load_cursorrules(cwd_path) # 4. .cursorrules / .cursor/rules/*.mdc
)
sections = []
if project_context:
sections.append(project_context)
# SOUL.md from KOPI_HOME (independent of project context)
if not skip_soul:
soul_content = load_soul_md()
if soul_content:
sections.append(soul_content)
if not sections:
return ""
return (
"# Project Context\n\n"
"The following project context files have been loaded "
"and should be followed:\n\n"
+ "\n".join(sections)
)
上下文文件发现细节
| 优先级 | 文件 | 搜索范围 | 备注 |
|---|---|---|---|
| 1 | .kopi.md, HERMES.md | 从 CWD 向上直到 git 根目录 | Kopi Agent 原生项目 config |
| 2 | AGENTS.md | 仅 CWD | 常见的 agent 指令文件 |
| 3 | CLAUDE.md | 仅 CWD | Claude Code 兼容 |
| 4 | .cursorrules, .cursor/rules/*.mdc | 仅 CWD | Cursor 兼容 |
所有上下文文件都会:
- 安全扫描 — 检查 prompt 注入模式(不可见 unicode、"ignore previous instructions"、凭据外泄企图)
- 截断 — 上限为
context_file_max_chars个字符(默认 20,000),采用 70/20 的头部/尾部比例,并添加截断标记 - 剥离 YAML frontmatter — 移除
.kopi.mdfrontmatter(预留给未来的 config 覆盖功能)
仅在 API 调用时生效的层级
以下内容刻意不作为缓存 system prompt 的一部分进行持久化:
ephemeral_system_prompt- prefill 消息
- 网关派生的会话上下文覆盖层
- 后续轮次的 Honcho/外部召回内容,注入到当前轮次的 user message 中
pre_llm_call plugin 上下文同样走这条 API 调用时路径:它会被追加到当前轮次的 user message 中,而不是写入缓存的 system prompt。当多个 plugin 返回上下文时,Kopi Agent 会拼接这些上下文区块(见 Hooks → pre_llm_call)。
这种分离确保了用于缓存的稳定前缀保持稳定。
Memory 快照
本地 memory 和用户画像数据会被捕获到 system prompt 的 volatile 层。会话中途的写入会更新磁盘状态,但不会修改已构建的缓存 system prompt,直到某个重建路径运行(新会话,或显式的失效/重建流程,例如压缩触发的重建)。
上下文文件
agent/prompt_builder.py 使用优先级系统扫描并清理项目上下文文件 —— 只加载一种类型(首个匹配项生效):
.kopi.md/HERMES.md(向上遍历到 git 根目录)AGENTS.md(启动时的 CWD;会话期间通过agent/subdirectory_hints.py逐步发现子目录)CLAUDE.md(仅 CWD).cursorrules/.cursor/rules/*.mdc(仅 CWD)
SOUL.md 通过 load_soul_md() 单独加载到身份槽位。当它成功加载时,build_context_files_prompt(skip_soul=True) 会防止它出现两次。
较长的文件在注入前会被截断。
Skills 索引
当 skills 工具链可用时,skills 系统会向 prompt 提供一个紧凑的 skills 索引。
支持的 prompt 定制入口
大多数用户应将 agent/prompt_builder.py 视为实现代码,而非配置入口。受支持的定制路径是修改 Kopi Agent 已加载的 prompt 输入,而不是直接编辑 Python 模板。
优先使用这些入口
~/.kopi/SOUL.md—— 用你自己的 agent 人设和长期行为规范替换内置的默认身份块。~/.kopi/MEMORY.md与~/.kopi/USER.md—— 提供跨会话持久的事实和用户资料数据,这些数据会被快照到新会话中。- 项目上下文文件,例如
.kopi.md、HERMES.md、AGENTS.md、CLAUDE.md或.cursorrules—— 注入仓库特定的工作规则。 - Skills —— 打包可复用的工作流和参考资料,无需修改核心 prompt 代码。
- 可选的 system prompt config / API overrides —— 添加部署特定的指令文本,无需 fork Kopi Agent。
- 临时覆盖层,例如
KOPI_EPHEMERAL_SYSTEM_PROMPT或 prefill 消息 —— 添加仅限当前轮次的指导内容,使其不会成为缓存 prompt 前缀的一部分。
何时应该直接改代码
只有在你有意维护一个 fork 或向 upstream 提交行为变更时,才应编辑 agent/prompt_builder.py。该文件负责组装每个会话的 prompt 管线、缓存边界和注入顺序。直接修改该文件属于全局产品变更,而非按用户维度的 prompt 定制。
换句话说:
- 如果你想更换 assistant 身份,编辑
SOUL.md - 如果你想更换仓库规则,编辑项目上下文文件
- 如果你想获得可复用的操作流程,添加或修改 skills
- 如果你想改变 Kopi Agent 为所有人组装 prompt 的方式,就修改 Python 代码,并将其作为一次代码贡献来对待
为什么 prompt 组装要这样拆分
该架构经过有意优化,目的是:
- 保留 provider(服务提供商)侧的 prompt caching
- 避免不必要地修改 history
- 让 memory 语义易于理解
- 让 gateway/ACP/CLI 能添加上下文,同时不污染持久化的 prompt 状态