一句话总结
Context Engineering = System Prompt + RAG + Tool + Memory + Metadata,五层叠加,缺一不可。
今天我们从零搭建一个完整的上下文工程系统,把前5篇学到的知识全部整合起来。
我们要构建什么?
一个智能写作助手,它能:
- 根据你的历史文章学习你的写作风格
- 从网上搜索最新素材
- 使用你指定的工具(图片生成、发布等)
- 记住你的偏好和历史
- 知道当前时间和任务
系统架构
`
┌─────────────────────────────────────────────────┐
│ 用户输入 │
└─────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────┐
│ Context Assembler(上下文组装器) │
│ ┌─────────────────────────────────────────────┐│
│ │ 第1层:System Prompt ││
│ │ – 角色定义 ││
│ │ – 行为约束 ││
│ │ – 输出格式 ││
│ └─────────────────────────────────────────────┘│
│ ┌─────────────────────────────────────────────┐│
│ │ 第2层:RAG ││
│ │ – 搜索相关文章 ││
│ │ – 检索参考资料 ││
│ └─────────────────────────────────────────────┘│
│ ┌─────────────────────────────────────────────┐│
│ │ 第3层:Tool Descriptions ││
│ │ – 图片生成工具 ││
│ │ – 发布工具 ││
│ │ – 搜索工具 ││
│ └─────────────────────────────────────────────┘│
│ ┌─────────────────────────────────────────────┐│
│ │ 第4层:Memory ││
│ │ – 用户偏好 ││
│ │ – 历史文章 ││
│ │ – 教训记录 ││
│ └─────────────────────────────────────────────┘│
│ ┌─────────────────────────────────────────────┐│
│ │ 第5层:Metadata ││
│ │ – 当前时间 ││
│ │ – 任务类型 ││
│ │ – 环境信息 ││
│ └─────────────────────────────────────────────┘│
└─────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────┐
│ LLM │
└─────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────┐
│ 输出 │
└─────────────────────────────────────────────────┘
`
第1步:定义System Prompt
`python
SYSTEM_PROMPT = “””
你是一位资深技术博主,公众号”攀岩者”的作者。
角色定位
- 技术总监,19年IT全栈实战
- 精通网络、安全、云计算、容器、数据库、超算
- 持证PMP、ITIL、CKA、网络工程师等
写作风格
- 亲切专业,像一位耐心的老师
- 善用类比和举例
- 结构清晰,重点加粗
- 长度约2500字(10-15分钟阅读)
约束
- 标题禁止emoji,只能用纯文字符号(●◆■▲★等)
- 必须包含天气banner
- 必须包含”地铁深读”板块
- 使用standard模板
输出格式
- Markdown格式
- 小标题分段
- 重点加粗
- 适当留白
“””
`
第2步:实现RAG检索
`python
from sentence_transformers import SentenceTransformer
import chromadb
class RAGRetriever:
def __init__(self):
self.model = SentenceTransformer(‘BAAI/bge-base-zh-v1.5’)
self.client = chromadb.PersistentClient(path=”./chroma_db”)
self.collection = self.client.get_or_create_collection(“articles”)
def add_article(self, article_id, content, metadata):
“””添加文章到知识库”””
embedding = self.model.encode(content)
self.collection.add(
ids=[article_id],
embeddings=[embedding.tolist()],
documents=[content],
metadatas=[metadata]
)
def search(self, query, top_k=5):
“””搜索相关文章”””
query_embedding = self.model.encode(query)
results = self.collection.query(
query_embeddings=[query_embedding.tolist()],
n_results=top_k
)
return results[‘documents’][0]
# 使用示例
retriever = RAGRetriever()
# 添加历史文章
retriever.add_article(
“day40”,
“今天学习AI搜索,包括秘塔AI、ChatGPT搜索等…”,
{“date”: “2026-06-26”, “type”: “早课”, “day”: 40}
)
# 搜索相关文章
related = retriever.search(“AI搜索”, top_k=3)
`
第3步:定义工具描述
`python
TOOLS = [
{
“name”: “generate_image”,
“description”: “根据描述生成配图”,
“parameters”: {
“prompt”: {
“type”: “string”,
“description”: “图片描述”,
“required”: True
},
“style”: {
“type”: “string”,
“description”: “图片风格”,
“default”: “科技感”,
“enum”: [“科技感”, “清新”, “商务”, “创意”]
}
},
“when_to_use”: “需要生成文章配图时”,
“when_not_to_use”: “使用已有图片时”
},
{
“name”: “publish_article”,
“description”: “发布文章到公众号和网站”,
“parameters”: {
“title”: {
“type”: “string”,
“description”: “文章标题”,
“required”: True
},
“content”: {
“type”: “string”,
“description”: “文章内容(Markdown格式)”,
“required”: True
},
“platforms”: {
“type”: “array”,
“description”: “发布平台”,
“default”: [“wechat”, “wordpress”]
}
},
“when_to_use”: “文章写完需要发布时”,
“when_not_to_use”: “文章还在草稿阶段时”
},
{
“name”: “search_news”,
“description”: “搜索最新AI新闻”,
“parameters”: {
“query”: {
“type”: “string”,
“description”: “搜索关键词”,
“required”: True
},
“time_range”: {
“type”: “string”,
“description”: “时间范围”,
“default”: “24h”
}
},
“when_to_use”: “需要获取最新素材时”,
“when_not_to_use”: “使用已有素材时”
}
]
`
第4步:实现记忆系统
`python
import json
from datetime import datetime
from pathlib import Path
class MemorySystem:
def __init__(self, memory_dir=”./memories”):
self.memory_dir = Path(memory_dir)
self.memory_dir.mkdir(exist_ok=True)
def save_preference(self, key, value):
“””保存用户偏好”””
prefs = self.load_preferences()
prefs[key] = {
“value”: value,
“updated_at”: datetime.now().isoformat()
}
with open(self.memory_dir / “preferences.json”, ‘w’) as f:
json.dump(prefs, f, ensure_ascii=False, indent=2)
def load_preferences(self):
“””加载用户偏好”””
path = self.memory_dir / “preferences.json”
if path.exists():
with open(path) as f:
return json.load(f)
return {}
def save_episode(self, content, metadata):
“””保存事件记录”””
episodes = self.load_episodes()
episodes.append({
“content”: content,
“metadata”: metadata,
“timestamp”: datetime.now().isoformat()
})
with open(self.memory_dir / “episodes.json”, ‘w’) as f:
json.dump(episodes, f, ensure_ascii=False, indent=2)
def load_episodes(self):
“””加载事件记录”””
path = self.memory_dir / “episodes.json”
if path.exists():
with open(path) as f:
return json.load(f)
return []
def save_lesson(self, lesson, confidence=0.5):
“””保存教训”””
lessons = self.load_lessons()
lessons.append({
“lesson”: lesson,
“confidence”: confidence,
“created_at”: datetime.now().isoformat(),
“reinforced_count”: 0
})
with open(self.memory_dir / “lessons.json”, ‘w’) as f:
json.dump(lessons, f, ensure_ascii=False, indent=2)
def load_lessons(self):
“””加载教训”””
path = self.memory_dir / “lessons.json”
if path.exists():
with open(path) as f:
return json.load(f)
return []
# 使用示例
memory = MemorySystem()
# 保存用户偏好
memory.save_preference(“style”, “亲切专业”)
memory.save_preference(“no_emoji”, True)
# 保存事件
memory.save_episode(
“Day40早课已发布,主题是AI搜索”,
{“day”: 40, “type”: “早课”, “status”: “已完成”}
)
# 保存教训
memory.save_lesson(
“标题不能用emoji,否则发布失败”,
confidence=0.9
)
`
第5步:实现上下文组装器
`python
class ContextAssembler:
def __init__(self, rag, memory, tools):
self.rag = rag
self.memory = memory
self.tools = tools
def assemble(self, user_message, task_type=”writing”):
“””组装完整上下文”””
context_parts = []
# 第1层:System Prompt
context_parts.append(f”n{SYSTEM_PROMPT}n”)
# 第2层:RAG检索
related_articles = self.rag.search(user_message, top_k=3)
if related_articles:
rag_context = “n”.join([
f”
”
for article in related_articles
])
context_parts.append(f”n{rag_context}n”)
# 第3层:Tool描述
relevant_tools = self._select_tools(task_type)
tools_context = json.dumps(relevant_tools, ensure_ascii=False, indent=2)
context_parts.append(f”n{tools_context}n”)
# 第4层:Memory
preferences = self.memory.load_preferences()
episodes = self.memory.load_episodes()[-5:] # 最近5条
lessons = self.memory.load_lessons()[-3:] # 最近3条
memory_context = {
“preferences”: preferences,
“recent_episodes”: episodes,
“lessons”: lessons
}
context_parts.append(f”n{json.dumps(memory_context, ensure_ascii=False, indent=2)}n”)
# 第5层:Metadata
metadata = {
“current_time”: datetime.now().isoformat(),
“task_type”: task_type,
“platform”: “Linux”
}
context_parts.append(f”n{json.dumps(metadata, ensure_ascii=False, indent=2)}n”)
# 用户输入
context_parts.append(f”n{user_message}n”)
return “nn”.join(context_parts)
def _select_tools(self, task_type):
“””根据任务类型选择工具”””
tool_map = {
“writing”: [“generate_image”, “publish_article”, “search_news”],
“research”: [“search_news”],
“coding”: [“read_file”, “write_file”, “terminal”]
}
tool_names = tool_map.get(task_type, [])
return [t for t in self.tools if t[‘name’] in tool_names]
`
第6步:完整使用示例
`python
# 初始化组件
rag = RAGRetriever()
memory = MemorySystem()
assembler = ContextAssembler(rag, memory, TOOLS)
# 用户输入
user_message = “帮我写一篇关于AI Agent的公众号文章”
# 组装上下文
context = assembler.assemble(user_message, task_type=”writing”)
# 发送给LLM
response = llm.generate(
system=SYSTEM_PROMPT,
context=context,
user_message=user_message
)
# 保存记忆
memory.save_episode(
f”写了关于AI Agent的文章”,
{“topic”: “AI Agent”, “type”: “公众号文章”}
)
# 发布文章
publish_article(response.title, response.content)
`
🚇 地铁深读:Context Engineering的未来
1. 自适应上下文
未来的AI会自己决定需要看什么材料:
`
用户问题 → AI分析需要什么信息 → 自动检索 → 动态组装
`
不需要人工预设上下文模板。
2. 上下文即代码
上下文策略可以版本控制、测试、部署:
`yaml
# context-config.yaml
version: “1.0”
layers:
- name: system_prompt
source: ./prompts/system.md
- name: rag
source: ./knowledge-base
top_k: 5
- name: memory
source: ./memories
max_items: 10
`
3. 多模态上下文
不只是文本,还有图片、音频、视频:
`python
context = {
“text”: “用户的问题”,
“images”: [“screenshot.png”],
“audio”: [“voice_message.mp3”],
“video”: [“demo_video.mp4”]
}
`
4. 上下文优化
自动优化上下文,提高效果:
`python
# A/B测试不同上下文策略
strategy_a = assemble_with_rag_top5()
strategy_b = assemble_with_rag_top10()
# 比较效果
evaluate(strategy_a, strategy_b)
`
今日小结
| 步骤 | 组件 | 作用 |
|---|
|——|——|——|
| 1 | System Prompt | 定义角色和规则 |
|---|---|---|
| 2 | RAG | 检索相关知识 |
| 3 | Tool描述 | 定义可用工具 |
| 4 | Memory | 存储偏好和历史 |
| 5 | Metadata | 注入环境信息 |
| 6 | Assembler | 组装完整上下文 |
一句话记住: Context Engineering = 五层叠加,让AI”看到”正确的材料,才能做出正确的回答。
系列回顾
| 篇号 | 标题 | 核心内容 |
|---|
|——|——|———-|
| 01 | 什么是Context Engineering | 定义、与Prompt区别、Karpathy观点 |
|---|---|---|
| 02 | Context的五层架构 | System/RAG/Tool/Memory/Metadata |
| 03 | RAG深度解析 | 分块、向量化、检索、重排序、注入 |
| 04 | 记忆管理 | 四层记忆、衰减、强化、反思 |
| 05 | 工具描述与动态组装 | 工具设计、Token预算、动态加载 |
| 06 | 实战:构建完整系统 | 从零搭建完整的上下文工程系统 |
*攀岩者 | 技术总监 | 19年IT全栈实战*
*每天分享AI学习笔记,陪你从零基础到AI达人*
发表回复