前言
书接上回:【小白成长之路】第五章:Prompt Engineering
Prompt 再精妙,一次对话也塞不下多少信息。当任务需要长文档、多轮记忆、复杂指令时,单靠 Prompt 就不够了。Context Engineering 关注的是:如何在有限的上下文窗口里,放对信息、放够信息、放好信息。
学习目标
- 理解 Context 的核心概念和 Token 限制原理
- 掌握 Context 优化的四大策略:压缩、切片、排序、格式化
- 能够设计长上下文处理方案:滑动窗口、分层摘要、RAG
- 理解记忆机制:短期记忆 vs 长期记忆的设计与检索
- 掌握多轮对话 Context 管理的实战技巧
- 识别并规避 Context 管理中的常见误区
详细内容
知识地图
#mermaid-svg-tLEs6sqITLR3xxDB{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-tLEs6sqITLR3xxDB .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-tLEs6sqITLR3xxDB .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-tLEs6sqITLR3xxDB .error-icon{fill:#552222;}#mermaid-svg-tLEs6sqITLR3xxDB .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-tLEs6sqITLR3xxDB .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-tLEs6sqITLR3xxDB .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-tLEs6sqITLR3xxDB .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-tLEs6sqITLR3xxDB .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-tLEs6sqITLR3xxDB .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-tLEs6sqITLR3xxDB .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-tLEs6sqITLR3xxDB .marker{fill:#333333;stroke:#333333;}#mermaid-svg-tLEs6sqITLR3xxDB .marker.cross{stroke:#333333;}#mermaid-svg-tLEs6sqITLR3xxDB svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-tLEs6sqITLR3xxDB p{margin:0;}#mermaid-svg-tLEs6sqITLR3xxDB .edge{stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .section--1 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section--1 path,#mermaid-svg-tLEs6sqITLR3xxDB .section--1 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section--1 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section--1 path{fill:hsl(240, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section--1 text{fill:#ffffff;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon--1{font-size:40px;color:#ffffff;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge--1{stroke:hsl(240, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth--1{stroke-width:17;}#mermaid-svg-tLEs6sqITLR3xxDB .section--1 line{stroke:hsl(60, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-0 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-0 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-0 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-0 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-0 path{fill:hsl(60, 100%, 73.5294117647%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-0 text{fill:black;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-0{font-size:40px;color:black;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-0{stroke:hsl(60, 100%, 73.5294117647%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-0{stroke-width:14;}#mermaid-svg-tLEs6sqITLR3xxDB .section-0 line{stroke:hsl(240, 100%, 83.5294117647%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-1 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-1 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-1 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-1 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-1 path{fill:hsl(80, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-1 text{fill:black;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-1{font-size:40px;color:black;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-1{stroke:hsl(80, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-1{stroke-width:11;}#mermaid-svg-tLEs6sqITLR3xxDB .section-1 line{stroke:hsl(260, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-2 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-2 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-2 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-2 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-2 path{fill:hsl(270, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-2 text{fill:#ffffff;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-2{font-size:40px;color:#ffffff;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-2{stroke:hsl(270, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-2{stroke-width:8;}#mermaid-svg-tLEs6sqITLR3xxDB .section-2 line{stroke:hsl(90, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-3 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-3 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-3 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-3 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-3 path{fill:hsl(300, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-3 text{fill:black;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-3{font-size:40px;color:black;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-3{stroke:hsl(300, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-3{stroke-width:5;}#mermaid-svg-tLEs6sqITLR3xxDB .section-3 line{stroke:hsl(120, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-4 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-4 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-4 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-4 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-4 path{fill:hsl(330, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-4 text{fill:black;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-4{font-size:40px;color:black;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-4{stroke:hsl(330, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-4{stroke-width:2;}#mermaid-svg-tLEs6sqITLR3xxDB .section-4 line{stroke:hsl(150, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-5 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-5 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-5 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-5 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-5 path{fill:hsl(0, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-5 text{fill:black;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-5{font-size:40px;color:black;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-5{stroke:hsl(0, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-5{stroke-width:-1;}#mermaid-svg-tLEs6sqITLR3xxDB .section-5 line{stroke:hsl(180, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-6 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-6 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-6 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-6 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-6 path{fill:hsl(30, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-6 text{fill:black;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-6{font-size:40px;color:black;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-6{stroke:hsl(30, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-6{stroke-width:-4;}#mermaid-svg-tLEs6sqITLR3xxDB .section-6 line{stroke:hsl(210, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-7 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-7 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-7 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-7 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-7 path{fill:hsl(90, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-7 text{fill:black;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-7{font-size:40px;color:black;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-7{stroke:hsl(90, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-7{stroke-width:-7;}#mermaid-svg-tLEs6sqITLR3xxDB .section-7 line{stroke:hsl(270, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-8 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-8 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-8 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-8 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-8 path{fill:hsl(150, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-8 text{fill:black;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-8{font-size:40px;color:black;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-8{stroke:hsl(150, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-8{stroke-width:-10;}#mermaid-svg-tLEs6sqITLR3xxDB .section-8 line{stroke:hsl(330, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-9 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-9 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-9 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-9 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-9 path{fill:hsl(180, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-9 text{fill:black;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-9{font-size:40px;color:black;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-9{stroke:hsl(180, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-9{stroke-width:-13;}#mermaid-svg-tLEs6sqITLR3xxDB .section-9 line{stroke:hsl(0, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-10 rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-10 path,#mermaid-svg-tLEs6sqITLR3xxDB .section-10 circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-10 polygon,#mermaid-svg-tLEs6sqITLR3xxDB .section-10 path{fill:hsl(210, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-10 text{fill:black;}#mermaid-svg-tLEs6sqITLR3xxDB .node-icon-10{font-size:40px;color:black;}#mermaid-svg-tLEs6sqITLR3xxDB .section-edge-10{stroke:hsl(210, 100%, 76.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .edge-depth-10{stroke-width:-16;}#mermaid-svg-tLEs6sqITLR3xxDB .section-10 line{stroke:hsl(30, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled,#mermaid-svg-tLEs6sqITLR3xxDB .disabled circle,#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:lightgray;}#mermaid-svg-tLEs6sqITLR3xxDB .disabled text{fill:#efefef;}#mermaid-svg-tLEs6sqITLR3xxDB .section-root rect,#mermaid-svg-tLEs6sqITLR3xxDB .section-root path,#mermaid-svg-tLEs6sqITLR3xxDB .section-root circle,#mermaid-svg-tLEs6sqITLR3xxDB .section-root polygon{fill:hsl(240, 100%, 46.2745098039%);}#mermaid-svg-tLEs6sqITLR3xxDB .section-root text{fill:#ffffff;}#mermaid-svg-tLEs6sqITLR3xxDB .section-root span{color:#ffffff;}#mermaid-svg-tLEs6sqITLR3xxDB .section-2 span{color:#ffffff;}#mermaid-svg-tLEs6sqITLR3xxDB .icon-container{height:100%;display:flex;justify-content:center;align-items:center;}#mermaid-svg-tLEs6sqITLR3xxDB .edge{fill:none;}#mermaid-svg-tLEs6sqITLR3xxDB .mindmap-node-label{dy:1em;alignment-baseline:middle;text-anchor:middle;dominant-baseline:middle;text-align:center;}#mermaid-svg-tLEs6sqITLR3xxDB :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} Context Engineering
6.1 Context 基础
Context 五要素
Token 与窗口限制
注意力 U 型分布
6.2 优化四策略
信息压缩 摘要/提取/分层
窗口管理 固定分块/重叠
优先级排序 三维打分
格式优化
6.3 高级技术
检索增强与外部记忆
Token 级压缩
长上下文窗口策略
6.4 记忆机制
短期 vs 长期
检索策略 复用6.2.3打分
更新与遗忘
6.5 多轮对话
历史截断
话题追踪
用户画像
6.6 实战
对话管理系统
AI 编程助手
6.7 常见误区
6.1 Context 基础
6.1.1 什么是 Context(上下文)
Context(上下文) 是指大语言模型(LLM)生成响应时,提供给模型的所有输入信息的总和。
| 组成部分 | 说明 | 示例 |
|---|---|---|
| 系统提示词 | 角色设定、任务约束、输出格式 | "你是一位资深数据分析师" |
| 用户输入 | 当前请求的具体内容 | "请分析这个销售数据集" |
| 历史对话 | 之前的多轮交互记录 | 前 5 轮问答内容 |
| 外部知识 | 检索增强生成(RAG)检索的文档片段 | 相关技术文档 3 篇 |
| 工具结果 | 函数调用/API 返回的数据 | 数据库查询结果 |
💡 类比理解 :Context 就像会议的背景资料包------参会者(模型)需要根据这些资料做决策。资料越精准充分,决策质量越高。

6.1.2 Token 限制与上下文窗口
Token是 LLM 处理文本的基本单位。理解 Token 限制是 Context Engineering 的第一步。
| 模型 | Context 窗口 | Token 计算(中文) | 典型应用场景 |
|---|---|---|---|
| GPT-4o | 128K | ~2 字符/token(因分词器而异) | 通用对话、代码生成 |
| Claude 3.5 Sonnet | 200K | ~2 字符/token(因分词器而异) | 长文档理解、合同分析 |
| Gemini 2.0 Pro | 200K | ~2 字符/token(因分词器而异) | 多模态、视频分析 |
| Qwen2.5 72B | 128K | ~1.5 字符/token(因分词器而异) | 中文长文本、代码 |
| DeepSeek V3 | 128K | ~1.5 字符/token(因分词器而异) | 代码生成、数学推理 |
⚠️ 重要提示:
- Context 窗口 ≠ 可用空间,需预留输出生成的 Token
- 实际可用 Context = 总窗口 - 预期输出长度
- 中文通常比英文占用更多 Token
6.1.3 注意力机制与 Context 的关系
Attention(注意力)机制决定了模型如何"关注"Context 中的不同部分。
#mermaid-svg-iZcySZbSRrJS7FNw{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-iZcySZbSRrJS7FNw .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-iZcySZbSRrJS7FNw .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-iZcySZbSRrJS7FNw .error-icon{fill:#552222;}#mermaid-svg-iZcySZbSRrJS7FNw .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-iZcySZbSRrJS7FNw .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-iZcySZbSRrJS7FNw .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-iZcySZbSRrJS7FNw .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-iZcySZbSRrJS7FNw .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-iZcySZbSRrJS7FNw .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-iZcySZbSRrJS7FNw .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-iZcySZbSRrJS7FNw .marker{fill:#333333;stroke:#333333;}#mermaid-svg-iZcySZbSRrJS7FNw .marker.cross{stroke:#333333;}#mermaid-svg-iZcySZbSRrJS7FNw svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-iZcySZbSRrJS7FNw p{margin:0;}#mermaid-svg-iZcySZbSRrJS7FNw .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-iZcySZbSRrJS7FNw .cluster-label text{fill:#333;}#mermaid-svg-iZcySZbSRrJS7FNw .cluster-label span{color:#333;}#mermaid-svg-iZcySZbSRrJS7FNw .cluster-label span p{background-color:transparent;}#mermaid-svg-iZcySZbSRrJS7FNw .label text,#mermaid-svg-iZcySZbSRrJS7FNw span{fill:#333;color:#333;}#mermaid-svg-iZcySZbSRrJS7FNw .node rect,#mermaid-svg-iZcySZbSRrJS7FNw .node circle,#mermaid-svg-iZcySZbSRrJS7FNw .node ellipse,#mermaid-svg-iZcySZbSRrJS7FNw .node polygon,#mermaid-svg-iZcySZbSRrJS7FNw .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-iZcySZbSRrJS7FNw .rough-node .label text,#mermaid-svg-iZcySZbSRrJS7FNw .node .label text,#mermaid-svg-iZcySZbSRrJS7FNw .image-shape .label,#mermaid-svg-iZcySZbSRrJS7FNw .icon-shape .label{text-anchor:middle;}#mermaid-svg-iZcySZbSRrJS7FNw .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-iZcySZbSRrJS7FNw .rough-node .label,#mermaid-svg-iZcySZbSRrJS7FNw .node .label,#mermaid-svg-iZcySZbSRrJS7FNw .image-shape .label,#mermaid-svg-iZcySZbSRrJS7FNw .icon-shape .label{text-align:center;}#mermaid-svg-iZcySZbSRrJS7FNw .node.clickable{cursor:pointer;}#mermaid-svg-iZcySZbSRrJS7FNw .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-iZcySZbSRrJS7FNw .arrowheadPath{fill:#333333;}#mermaid-svg-iZcySZbSRrJS7FNw .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-iZcySZbSRrJS7FNw .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-iZcySZbSRrJS7FNw .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-iZcySZbSRrJS7FNw .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-iZcySZbSRrJS7FNw .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-iZcySZbSRrJS7FNw .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-iZcySZbSRrJS7FNw .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-iZcySZbSRrJS7FNw .cluster text{fill:#333;}#mermaid-svg-iZcySZbSRrJS7FNw .cluster span{color:#333;}#mermaid-svg-iZcySZbSRrJS7FNw div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-iZcySZbSRrJS7FNw .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-iZcySZbSRrJS7FNw rect.text{fill:none;stroke-width:0;}#mermaid-svg-iZcySZbSRrJS7FNw .icon-shape,#mermaid-svg-iZcySZbSRrJS7FNw .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-iZcySZbSRrJS7FNw .icon-shape p,#mermaid-svg-iZcySZbSRrJS7FNw .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-iZcySZbSRrJS7FNw .icon-shape .label rect,#mermaid-svg-iZcySZbSRrJS7FNw .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-iZcySZbSRrJS7FNw .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-iZcySZbSRrJS7FNw .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-iZcySZbSRrJS7FNw :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 输入 Context
Query 生成
Key 生成
Value 生成
Attention 分数计算
Softmax 归一化
加权求和
输出表示
Attention 简化公式
Attention(Q, K, V) = softmax(QK^T / √d) × V
其中 Q=Query(查询向量),K=Key(键向量),V=Value(值向量),d=向量维度。
关键洞察
| 现象 | 说明 | 影响 |
|---|---|---|
| 注意力稀释 | Context 越长,单个 Token 分到的注意力越少 | 关键信息可能被忽略 |
| 位置偏倚 | 模型倾向于关注开头和结尾(U 型分布) | 中间信息容易被遗忘 |
| Lost in the Middle | 放置在 Context 中间的信息召回率最低 | 重要内容应放两端 |
#mermaid-svg-VkIGQWNIcPjJy4OI{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-VkIGQWNIcPjJy4OI .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-VkIGQWNIcPjJy4OI .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-VkIGQWNIcPjJy4OI .error-icon{fill:#552222;}#mermaid-svg-VkIGQWNIcPjJy4OI .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-VkIGQWNIcPjJy4OI .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-VkIGQWNIcPjJy4OI .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-VkIGQWNIcPjJy4OI .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-VkIGQWNIcPjJy4OI .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-VkIGQWNIcPjJy4OI .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-VkIGQWNIcPjJy4OI .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-VkIGQWNIcPjJy4OI .marker{fill:#333333;stroke:#333333;}#mermaid-svg-VkIGQWNIcPjJy4OI .marker.cross{stroke:#333333;}#mermaid-svg-VkIGQWNIcPjJy4OI svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-VkIGQWNIcPjJy4OI p{margin:0;}#mermaid-svg-VkIGQWNIcPjJy4OI :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 典型注意力分布(U 型曲线) 开头 1-10% 中前 10-30% 中间 30-70% 中后 70-90% 结尾 90-100% 40 35 30 25 20 15 10 5 0 注意力权重%
🎯 实战建议:
- 重要信息放两端:将关键指令放在 Context 开头或结尾
- 相关前文优先:保留与当前任务最相关的历史对话
- 结构化组织:使用清晰的标记和分隔符帮助模型定位
6.2 Context 优化核心策略
本节介绍 4 种基础优化策略,适用于大多数 Context 管理场景。
💡 过渡说明:这 4 种策略是 Context Engineering 的基本功,无论对话长短都应该掌握。当单一策略不足以解决问题时(如超长对话超过上下文窗口),需要组合使用多种策略,见 6.3 节。
6.2.1 信息压缩
当 Context 接近限制时,需要对信息进行压缩,保留核心内容。
6.2.1.1 方法一:摘要压缩
用 LLM 将长文本概括为简短摘要,压缩率可达 10-30%。
#mermaid-svg-xXoECcssDy3uXmHo{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-xXoECcssDy3uXmHo .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-xXoECcssDy3uXmHo .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-xXoECcssDy3uXmHo .error-icon{fill:#552222;}#mermaid-svg-xXoECcssDy3uXmHo .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-xXoECcssDy3uXmHo .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-xXoECcssDy3uXmHo .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-xXoECcssDy3uXmHo .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-xXoECcssDy3uXmHo .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-xXoECcssDy3uXmHo .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-xXoECcssDy3uXmHo .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-xXoECcssDy3uXmHo .marker{fill:#333333;stroke:#333333;}#mermaid-svg-xXoECcssDy3uXmHo .marker.cross{stroke:#333333;}#mermaid-svg-xXoECcssDy3uXmHo svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-xXoECcssDy3uXmHo p{margin:0;}#mermaid-svg-xXoECcssDy3uXmHo .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-xXoECcssDy3uXmHo .cluster-label text{fill:#333;}#mermaid-svg-xXoECcssDy3uXmHo .cluster-label span{color:#333;}#mermaid-svg-xXoECcssDy3uXmHo .cluster-label span p{background-color:transparent;}#mermaid-svg-xXoECcssDy3uXmHo .label text,#mermaid-svg-xXoECcssDy3uXmHo span{fill:#333;color:#333;}#mermaid-svg-xXoECcssDy3uXmHo .node rect,#mermaid-svg-xXoECcssDy3uXmHo .node circle,#mermaid-svg-xXoECcssDy3uXmHo .node ellipse,#mermaid-svg-xXoECcssDy3uXmHo .node polygon,#mermaid-svg-xXoECcssDy3uXmHo .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-xXoECcssDy3uXmHo .rough-node .label text,#mermaid-svg-xXoECcssDy3uXmHo .node .label text,#mermaid-svg-xXoECcssDy3uXmHo .image-shape .label,#mermaid-svg-xXoECcssDy3uXmHo .icon-shape .label{text-anchor:middle;}#mermaid-svg-xXoECcssDy3uXmHo .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-xXoECcssDy3uXmHo .rough-node .label,#mermaid-svg-xXoECcssDy3uXmHo .node .label,#mermaid-svg-xXoECcssDy3uXmHo .image-shape .label,#mermaid-svg-xXoECcssDy3uXmHo .icon-shape .label{text-align:center;}#mermaid-svg-xXoECcssDy3uXmHo .node.clickable{cursor:pointer;}#mermaid-svg-xXoECcssDy3uXmHo .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-xXoECcssDy3uXmHo .arrowheadPath{fill:#333333;}#mermaid-svg-xXoECcssDy3uXmHo .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-xXoECcssDy3uXmHo .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-xXoECcssDy3uXmHo .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-xXoECcssDy3uXmHo .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-xXoECcssDy3uXmHo .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-xXoECcssDy3uXmHo .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-xXoECcssDy3uXmHo .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-xXoECcssDy3uXmHo .cluster text{fill:#333;}#mermaid-svg-xXoECcssDy3uXmHo .cluster span{color:#333;}#mermaid-svg-xXoECcssDy3uXmHo div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-xXoECcssDy3uXmHo .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-xXoECcssDy3uXmHo rect.text{fill:none;stroke-width:0;}#mermaid-svg-xXoECcssDy3uXmHo .icon-shape,#mermaid-svg-xXoECcssDy3uXmHo .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-xXoECcssDy3uXmHo .icon-shape p,#mermaid-svg-xXoECcssDy3uXmHo .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-xXoECcssDy3uXmHo .icon-shape .label rect,#mermaid-svg-xXoECcssDy3uXmHo .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-xXoECcssDy3uXmHo .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-xXoECcssDy3uXmHo .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-xXoECcssDy3uXmHo :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 原始文本
10000 tokens
摘要模型
压缩摘要
500 tokens
主模型 Context
6.2.1.2 方法二:信息提取
从对话中提取关键信息为结构化数据(JSON),压缩率可达 5-10%。
python
def extract_key_info(conversation: list) -> dict:
"""从多轮对话中提取结构化关键信息"""
prompt = """分析以下对话,提取关键信息为 JSON:
- user_intent: 用户意图
- entities: 提及的实体(人名/项目/技术)
- decisions: 已做出的决策
- open_questions: 未解决的问题
对话内容:
"""
result = llm_generate(prompt + format_conversation(conversation))
return json.loads(result)
# 示例:5 轮对话(~2000 tokens)→ 提取结果(~100 tokens)
# {
# "user_intent": "搭建 RAG 系统",
# "entities": ["ChromaDB", "OpenAI", "Python"],
# "decisions": ["使用向量数据库存储文档", "选择余弦相似度检索"],
# "open_questions": ["是否需要重排序?"]
# }
💡 提取 vs 摘要的区别 :摘要保留叙述性信息("用户想搭建 RAG 系统,讨论了向量数据库选型"),提取保留结构化信息(
{"intent": "搭建RAG", "entities": ["ChromaDB"]})。提取更适合需要精确查询的场景,摘要更适合需要理解上下文的场景。
6.2.1.3 方法三:分层摘要(递归压缩)
对摘要再摘要,实现多层压缩,适用于超长文本。
#mermaid-svg-bIZMtO9EZhBp89eG{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-bIZMtO9EZhBp89eG .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-bIZMtO9EZhBp89eG .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-bIZMtO9EZhBp89eG .error-icon{fill:#552222;}#mermaid-svg-bIZMtO9EZhBp89eG .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-bIZMtO9EZhBp89eG .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-bIZMtO9EZhBp89eG .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-bIZMtO9EZhBp89eG .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-bIZMtO9EZhBp89eG .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-bIZMtO9EZhBp89eG .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-bIZMtO9EZhBp89eG .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-bIZMtO9EZhBp89eG .marker{fill:#333333;stroke:#333333;}#mermaid-svg-bIZMtO9EZhBp89eG .marker.cross{stroke:#333333;}#mermaid-svg-bIZMtO9EZhBp89eG svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-bIZMtO9EZhBp89eG p{margin:0;}#mermaid-svg-bIZMtO9EZhBp89eG .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-bIZMtO9EZhBp89eG .cluster-label text{fill:#333;}#mermaid-svg-bIZMtO9EZhBp89eG .cluster-label span{color:#333;}#mermaid-svg-bIZMtO9EZhBp89eG .cluster-label span p{background-color:transparent;}#mermaid-svg-bIZMtO9EZhBp89eG .label text,#mermaid-svg-bIZMtO9EZhBp89eG span{fill:#333;color:#333;}#mermaid-svg-bIZMtO9EZhBp89eG .node rect,#mermaid-svg-bIZMtO9EZhBp89eG .node circle,#mermaid-svg-bIZMtO9EZhBp89eG .node ellipse,#mermaid-svg-bIZMtO9EZhBp89eG .node polygon,#mermaid-svg-bIZMtO9EZhBp89eG .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-bIZMtO9EZhBp89eG .rough-node .label text,#mermaid-svg-bIZMtO9EZhBp89eG .node .label text,#mermaid-svg-bIZMtO9EZhBp89eG .image-shape .label,#mermaid-svg-bIZMtO9EZhBp89eG .icon-shape .label{text-anchor:middle;}#mermaid-svg-bIZMtO9EZhBp89eG .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-bIZMtO9EZhBp89eG .rough-node .label,#mermaid-svg-bIZMtO9EZhBp89eG .node .label,#mermaid-svg-bIZMtO9EZhBp89eG .image-shape .label,#mermaid-svg-bIZMtO9EZhBp89eG .icon-shape .label{text-align:center;}#mermaid-svg-bIZMtO9EZhBp89eG .node.clickable{cursor:pointer;}#mermaid-svg-bIZMtO9EZhBp89eG .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-bIZMtO9EZhBp89eG .arrowheadPath{fill:#333333;}#mermaid-svg-bIZMtO9EZhBp89eG .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-bIZMtO9EZhBp89eG .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-bIZMtO9EZhBp89eG .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-bIZMtO9EZhBp89eG .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-bIZMtO9EZhBp89eG .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-bIZMtO9EZhBp89eG .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-bIZMtO9EZhBp89eG .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-bIZMtO9EZhBp89eG .cluster text{fill:#333;}#mermaid-svg-bIZMtO9EZhBp89eG .cluster span{color:#333;}#mermaid-svg-bIZMtO9EZhBp89eG div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-bIZMtO9EZhBp89eG .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-bIZMtO9EZhBp89eG rect.text{fill:none;stroke-width:0;}#mermaid-svg-bIZMtO9EZhBp89eG .icon-shape,#mermaid-svg-bIZMtO9EZhBp89eG .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-bIZMtO9EZhBp89eG .icon-shape p,#mermaid-svg-bIZMtO9EZhBp89eG .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-bIZMtO9EZhBp89eG .icon-shape .label rect,#mermaid-svg-bIZMtO9EZhBp89eG .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-bIZMtO9EZhBp89eG .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-bIZMtO9EZhBp89eG .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-bIZMtO9EZhBp89eG :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 细节问题
概览问题
原始文档
100K tokens
第一层摘要
10K tokens
第二层摘要
1K tokens
最终摘要
200 tokens
用户提问
匹配层级
💡 分层 vs 单层:单层摘要适合中等长度(<10K tokens),分层摘要适合超长文本(>10K tokens)。分层摘要的优势是保留了不同粒度的信息------用户概览问题时用顶层摘要,需要细节时可以下探到对应层级的摘要。
6.2.2 窗口管理
当文本超长时,需要切分成多个块分别处理,并保持连贯性。
6.2.2.1 方法一:固定大小分块
将长文本按固定 Token 数切割,每块独立处理。这是最简单的分块方式,适合文档处理等不需要严格上下文连贯的场景。
python
def fixed_size_chunk(text: str, chunk_size: int = 500, encoding_name: str = "cl100k_base") -> list:
"""固定大小分块"""
tokens = tokenize(text, encoding_name)
chunks = []
for i in range(0, len(tokens), chunk_size):
chunk_tokens = tokens[i:i + chunk_size]
chunks.append(detokenize(chunk_tokens))
return chunks
# 示例:10K tokens 的文档 → 20 个 500-token 的分块
# 每个 chunk 独立送入 LLM 处理
| 参数 | 推荐值 | 说明 |
|---|---|---|
chunk_size |
256-512 | 分块大小,过小丢失上下文,过大超过窗口 |
| 切分依据 | Token 数 | 比字符数更精确(中文 1 字符 ≈ 1-2 tokens) |
⚠️ 固定分块的问题 :可能在句子中间截断,导致语义不完整。改进方法是按句子/段落边界切分,找到最近的句号或换行符作为切分点。
6.2.2.2 方法二:重叠窗口
重叠窗口保持上下文连贯性,避免信息在边界处丢失。
#mermaid-svg-6F2vXHvcfkzRUKcD{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-6F2vXHvcfkzRUKcD .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-6F2vXHvcfkzRUKcD .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-6F2vXHvcfkzRUKcD .error-icon{fill:#552222;}#mermaid-svg-6F2vXHvcfkzRUKcD .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-6F2vXHvcfkzRUKcD .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-6F2vXHvcfkzRUKcD .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-6F2vXHvcfkzRUKcD .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-6F2vXHvcfkzRUKcD .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-6F2vXHvcfkzRUKcD .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-6F2vXHvcfkzRUKcD .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-6F2vXHvcfkzRUKcD .marker{fill:#333333;stroke:#333333;}#mermaid-svg-6F2vXHvcfkzRUKcD .marker.cross{stroke:#333333;}#mermaid-svg-6F2vXHvcfkzRUKcD svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-6F2vXHvcfkzRUKcD p{margin:0;}#mermaid-svg-6F2vXHvcfkzRUKcD .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-6F2vXHvcfkzRUKcD .cluster-label text{fill:#333;}#mermaid-svg-6F2vXHvcfkzRUKcD .cluster-label span{color:#333;}#mermaid-svg-6F2vXHvcfkzRUKcD .cluster-label span p{background-color:transparent;}#mermaid-svg-6F2vXHvcfkzRUKcD .label text,#mermaid-svg-6F2vXHvcfkzRUKcD span{fill:#333;color:#333;}#mermaid-svg-6F2vXHvcfkzRUKcD .node rect,#mermaid-svg-6F2vXHvcfkzRUKcD .node circle,#mermaid-svg-6F2vXHvcfkzRUKcD .node ellipse,#mermaid-svg-6F2vXHvcfkzRUKcD .node polygon,#mermaid-svg-6F2vXHvcfkzRUKcD .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-6F2vXHvcfkzRUKcD .rough-node .label text,#mermaid-svg-6F2vXHvcfkzRUKcD .node .label text,#mermaid-svg-6F2vXHvcfkzRUKcD .image-shape .label,#mermaid-svg-6F2vXHvcfkzRUKcD .icon-shape .label{text-anchor:middle;}#mermaid-svg-6F2vXHvcfkzRUKcD .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-6F2vXHvcfkzRUKcD .rough-node .label,#mermaid-svg-6F2vXHvcfkzRUKcD .node .label,#mermaid-svg-6F2vXHvcfkzRUKcD .image-shape .label,#mermaid-svg-6F2vXHvcfkzRUKcD .icon-shape .label{text-align:center;}#mermaid-svg-6F2vXHvcfkzRUKcD .node.clickable{cursor:pointer;}#mermaid-svg-6F2vXHvcfkzRUKcD .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-6F2vXHvcfkzRUKcD .arrowheadPath{fill:#333333;}#mermaid-svg-6F2vXHvcfkzRUKcD .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-6F2vXHvcfkzRUKcD .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-6F2vXHvcfkzRUKcD .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-6F2vXHvcfkzRUKcD .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-6F2vXHvcfkzRUKcD .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-6F2vXHvcfkzRUKcD .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-6F2vXHvcfkzRUKcD .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-6F2vXHvcfkzRUKcD .cluster text{fill:#333;}#mermaid-svg-6F2vXHvcfkzRUKcD .cluster span{color:#333;}#mermaid-svg-6F2vXHvcfkzRUKcD div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-6F2vXHvcfkzRUKcD .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-6F2vXHvcfkzRUKcD rect.text{fill:none;stroke-width:0;}#mermaid-svg-6F2vXHvcfkzRUKcD .icon-shape,#mermaid-svg-6F2vXHvcfkzRUKcD .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-6F2vXHvcfkzRUKcD .icon-shape p,#mermaid-svg-6F2vXHvcfkzRUKcD .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-6F2vXHvcfkzRUKcD .icon-shape .label rect,#mermaid-svg-6F2vXHvcfkzRUKcD .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-6F2vXHvcfkzRUKcD .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-6F2vXHvcfkzRUKcD .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-6F2vXHvcfkzRUKcD :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 原始文本
重叠 200
重叠 200
窗口 1: 0-1000
窗口 2: 800-1800
窗口 3: 1600-2600
python
def sliding_window_chunk(text: str, window_size: int = 1000, overlap: int = 200) -> list:
"""带重叠的滑动窗口分块"""
tokens = tokenize(text)
chunks = []
step = window_size - overlap # 步长 = 窗口 - 重叠
for i in range(0, len(tokens), step):
chunk_tokens = tokens[i:i + window_size]
chunks.append(detokenize(chunk_tokens))
return chunks
重叠窗口参数选择
| 重叠比例 | 适用场景 | 特点 |
|---|---|---|
| 10-15% | 文档问答、信息检索 | 轻度重叠,节省 Token |
| 15-25% | 对话历史、连续叙事 | 平衡连贯性和效率 |
| 25-50% | 代码分析、严格上下文 | 高重叠,确保不丢失 |
💡 边界信息丢失怎么办:如果关键信息恰好在两个窗口的边界处,重叠区域可以"兜底"------它在两个窗口中都会出现,确保至少有一个完整的上下文。
6.2.3 优先级排序
当 Context 空间有限时,根据重要性选择保留哪些信息。核心思路是给每条信息打分,按分数从高到低填充 Context,直到预算用完。
三维打分模型
| 维度 | 权重 | 说明 | 示例 |
|---|---|---|---|
| 相关性 | 0.4 | 与当前任务的语义相关程度 | 问代码问题时,代码片段 > 闲聊记录 |
| 时效性 | 0.3 | 信息的新鲜程度 | 最近的对话 > 三天前的对话 |
| 重要性 | 0.3 | 信息的不可替代程度 | 关键决策 > 常识性描述 |
#mermaid-svg-AkweSj84Vb5tobLe{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-AkweSj84Vb5tobLe .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-AkweSj84Vb5tobLe .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-AkweSj84Vb5tobLe .error-icon{fill:#552222;}#mermaid-svg-AkweSj84Vb5tobLe .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-AkweSj84Vb5tobLe .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-AkweSj84Vb5tobLe .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-AkweSj84Vb5tobLe .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-AkweSj84Vb5tobLe .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-AkweSj84Vb5tobLe .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-AkweSj84Vb5tobLe .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-AkweSj84Vb5tobLe .marker{fill:#333333;stroke:#333333;}#mermaid-svg-AkweSj84Vb5tobLe .marker.cross{stroke:#333333;}#mermaid-svg-AkweSj84Vb5tobLe svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-AkweSj84Vb5tobLe p{margin:0;}#mermaid-svg-AkweSj84Vb5tobLe .edge{stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .section--1 rect,#mermaid-svg-AkweSj84Vb5tobLe .section--1 path,#mermaid-svg-AkweSj84Vb5tobLe .section--1 circle,#mermaid-svg-AkweSj84Vb5tobLe .section--1 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section--1 path{fill:hsl(240, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section--1 text{fill:#ffffff;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon--1{font-size:40px;color:#ffffff;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge--1{stroke:hsl(240, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth--1{stroke-width:17;}#mermaid-svg-AkweSj84Vb5tobLe .section--1 line{stroke:hsl(60, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-0 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-0 path,#mermaid-svg-AkweSj84Vb5tobLe .section-0 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-0 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-0 path{fill:hsl(60, 100%, 73.5294117647%);}#mermaid-svg-AkweSj84Vb5tobLe .section-0 text{fill:black;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-0{font-size:40px;color:black;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-0{stroke:hsl(60, 100%, 73.5294117647%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-0{stroke-width:14;}#mermaid-svg-AkweSj84Vb5tobLe .section-0 line{stroke:hsl(240, 100%, 83.5294117647%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-1 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-1 path,#mermaid-svg-AkweSj84Vb5tobLe .section-1 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-1 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-1 path{fill:hsl(80, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-1 text{fill:black;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-1{font-size:40px;color:black;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-1{stroke:hsl(80, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-1{stroke-width:11;}#mermaid-svg-AkweSj84Vb5tobLe .section-1 line{stroke:hsl(260, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-2 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-2 path,#mermaid-svg-AkweSj84Vb5tobLe .section-2 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-2 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-2 path{fill:hsl(270, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-2 text{fill:#ffffff;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-2{font-size:40px;color:#ffffff;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-2{stroke:hsl(270, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-2{stroke-width:8;}#mermaid-svg-AkweSj84Vb5tobLe .section-2 line{stroke:hsl(90, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-3 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-3 path,#mermaid-svg-AkweSj84Vb5tobLe .section-3 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-3 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-3 path{fill:hsl(300, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-3 text{fill:black;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-3{font-size:40px;color:black;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-3{stroke:hsl(300, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-3{stroke-width:5;}#mermaid-svg-AkweSj84Vb5tobLe .section-3 line{stroke:hsl(120, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-4 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-4 path,#mermaid-svg-AkweSj84Vb5tobLe .section-4 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-4 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-4 path{fill:hsl(330, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-4 text{fill:black;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-4{font-size:40px;color:black;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-4{stroke:hsl(330, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-4{stroke-width:2;}#mermaid-svg-AkweSj84Vb5tobLe .section-4 line{stroke:hsl(150, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-5 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-5 path,#mermaid-svg-AkweSj84Vb5tobLe .section-5 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-5 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-5 path{fill:hsl(0, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-5 text{fill:black;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-5{font-size:40px;color:black;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-5{stroke:hsl(0, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-5{stroke-width:-1;}#mermaid-svg-AkweSj84Vb5tobLe .section-5 line{stroke:hsl(180, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-6 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-6 path,#mermaid-svg-AkweSj84Vb5tobLe .section-6 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-6 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-6 path{fill:hsl(30, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-6 text{fill:black;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-6{font-size:40px;color:black;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-6{stroke:hsl(30, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-6{stroke-width:-4;}#mermaid-svg-AkweSj84Vb5tobLe .section-6 line{stroke:hsl(210, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-7 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-7 path,#mermaid-svg-AkweSj84Vb5tobLe .section-7 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-7 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-7 path{fill:hsl(90, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-7 text{fill:black;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-7{font-size:40px;color:black;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-7{stroke:hsl(90, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-7{stroke-width:-7;}#mermaid-svg-AkweSj84Vb5tobLe .section-7 line{stroke:hsl(270, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-8 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-8 path,#mermaid-svg-AkweSj84Vb5tobLe .section-8 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-8 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-8 path{fill:hsl(150, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-8 text{fill:black;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-8{font-size:40px;color:black;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-8{stroke:hsl(150, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-8{stroke-width:-10;}#mermaid-svg-AkweSj84Vb5tobLe .section-8 line{stroke:hsl(330, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-9 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-9 path,#mermaid-svg-AkweSj84Vb5tobLe .section-9 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-9 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-9 path{fill:hsl(180, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-9 text{fill:black;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-9{font-size:40px;color:black;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-9{stroke:hsl(180, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-9{stroke-width:-13;}#mermaid-svg-AkweSj84Vb5tobLe .section-9 line{stroke:hsl(0, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-10 rect,#mermaid-svg-AkweSj84Vb5tobLe .section-10 path,#mermaid-svg-AkweSj84Vb5tobLe .section-10 circle,#mermaid-svg-AkweSj84Vb5tobLe .section-10 polygon,#mermaid-svg-AkweSj84Vb5tobLe .section-10 path{fill:hsl(210, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-10 text{fill:black;}#mermaid-svg-AkweSj84Vb5tobLe .node-icon-10{font-size:40px;color:black;}#mermaid-svg-AkweSj84Vb5tobLe .section-edge-10{stroke:hsl(210, 100%, 76.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .edge-depth-10{stroke-width:-16;}#mermaid-svg-AkweSj84Vb5tobLe .section-10 line{stroke:hsl(30, 100%, 86.2745098039%);stroke-width:3;}#mermaid-svg-AkweSj84Vb5tobLe .disabled,#mermaid-svg-AkweSj84Vb5tobLe .disabled circle,#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:lightgray;}#mermaid-svg-AkweSj84Vb5tobLe .disabled text{fill:#efefef;}#mermaid-svg-AkweSj84Vb5tobLe .section-root rect,#mermaid-svg-AkweSj84Vb5tobLe .section-root path,#mermaid-svg-AkweSj84Vb5tobLe .section-root circle,#mermaid-svg-AkweSj84Vb5tobLe .section-root polygon{fill:hsl(240, 100%, 46.2745098039%);}#mermaid-svg-AkweSj84Vb5tobLe .section-root text{fill:#ffffff;}#mermaid-svg-AkweSj84Vb5tobLe .section-root span{color:#ffffff;}#mermaid-svg-AkweSj84Vb5tobLe .section-2 span{color:#ffffff;}#mermaid-svg-AkweSj84Vb5tobLe .icon-container{height:100%;display:flex;justify-content:center;align-items:center;}#mermaid-svg-AkweSj84Vb5tobLe .edge{fill:none;}#mermaid-svg-AkweSj84Vb5tobLe .mindmap-node-label{dy:1em;alignment-baseline:middle;text-anchor:middle;dominant-baseline:middle;text-align:center;}#mermaid-svg-AkweSj84Vb5tobLe :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 优先级排序
相关性 0.4
与当前问题语义相似
涉及相同实体/主题
使用向量相似度计算
时效性 0.3
越新的信息权重越高
时间指数衰减
half_life 可调节
重要性 0.3
关键决策/结论
用户明确标注
不可从其他信息推导
python
class PrioritySelector:
"""基于三维打分的优先级排序器"""
def __init__(self, relevance_w=0.4, recency_w=0.3, importance_w=0.3):
self.weights = {"relevance": relevance_w, "recency": recency_w, "importance": importance_w}
def score(self, item: dict, current_query: str) -> float:
relevance = cosine_similarity(get_embedding(item["content"]), get_embedding(current_query))
recency = math.pow(2, -(time.time() - item["timestamp"]) / 3600) # 半衰期 1 小时
importance = item.get("importance", 0.5)
return (self.weights["relevance"] * relevance +
self.weights["recency"] * recency +
self.weights["importance"] * importance)
def select(self, items: list, current_query: str, max_tokens: int) -> list:
"""选择优先级最高的项目,不超过 Token 预算"""
scored = [(self.score(item, current_query), item) for item in items]
scored.sort(reverse=True)
selected, total = [], 0
for score, item in scored:
tokens = estimate_tokens(item["content"])
if total + tokens > max_tokens:
break
selected.append(item)
total += tokens
return selected
🎯 权重调整建议:
- 客服场景 :提高时效性权重(最新问题最重要),如
0.3 / 0.5 / 0.2- 知识问答 :提高相关性权重(找到最相关文档最重要),如
0.5 / 0.2 / 0.3- 项目管理 :提高重要性权重(关键决策不能丢),如
0.2 / 0.3 / 0.5
6.2.4 格式优化
减少 Token 浪费,用更简洁的格式表达相同内容。
| 问题类型 | 优化方案 | 节省比例 |
|---|---|---|
| 冗余标记 | <user_message>你好</user_message> → User: 你好 |
~40% |
| 过度解释 | "我想请你帮我分析一下..." → 直接给出任务 | ~30% |
| 重复信息 | 多次提及同一背景 → 结构化整理,只出现一次 | ~50% |
| 冗长示例 | 完整的长对话示例 → 精简到核心模式 | ~60% |
🎯 格式优化清单:移除客套话、使用结构化格式、示例精简到最小必要、避免重复背景说明。
6.3 高级 Context 技术
💡 过渡说明 :6.2 节的 4 种策略适用于大多数场景。但当面对超长 Context(如 100K+ tokens 的文档、数月历史的对话)时,需要更强大的架构级技术------把信息存到外部,按需检索,而不是全塞进 Context。
6.3.1 检索增强与外部记忆
系统架构
先看全局:Context 管理系统的完整架构是 基础优化策略(6.2)+ 检索与外部记忆(6.3)+ 记忆机制(6.4) 三层,本节聚焦其中的检索与外部记忆层。

💡 设计原则:
- 分层处理:先优化(6.2 压缩/排序/格式),后检索(6.3)
- 按需检索:只检索与当前任务最相关的信息
- 记忆分离:短期记忆放 Context,长期记忆放外部存储
核心思想
不把所有内容塞进 Context,而是存到外部向量库,按需检索最相关片段拼进去。无论检索的是静态知识库(RAG)还是动态记忆,底层机制相同。
向量检索流程
任何文本存入向量库前,先经 Embedding 模型转为向量------语义相近的文本在向量空间中距离更近;查询时同样向量化,做最近邻搜索取 Top-K 最相关片段,拼接到 Context 交给 LLM:
#mermaid-svg-DgvqiBkXMDIvSZzV{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-DgvqiBkXMDIvSZzV .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-DgvqiBkXMDIvSZzV .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-DgvqiBkXMDIvSZzV .error-icon{fill:#552222;}#mermaid-svg-DgvqiBkXMDIvSZzV .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-DgvqiBkXMDIvSZzV .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-DgvqiBkXMDIvSZzV .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-DgvqiBkXMDIvSZzV .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-DgvqiBkXMDIvSZzV .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-DgvqiBkXMDIvSZzV .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-DgvqiBkXMDIvSZzV .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-DgvqiBkXMDIvSZzV .marker{fill:#333333;stroke:#333333;}#mermaid-svg-DgvqiBkXMDIvSZzV .marker.cross{stroke:#333333;}#mermaid-svg-DgvqiBkXMDIvSZzV svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-DgvqiBkXMDIvSZzV p{margin:0;}#mermaid-svg-DgvqiBkXMDIvSZzV .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-DgvqiBkXMDIvSZzV .cluster-label text{fill:#333;}#mermaid-svg-DgvqiBkXMDIvSZzV .cluster-label span{color:#333;}#mermaid-svg-DgvqiBkXMDIvSZzV .cluster-label span p{background-color:transparent;}#mermaid-svg-DgvqiBkXMDIvSZzV .label text,#mermaid-svg-DgvqiBkXMDIvSZzV span{fill:#333;color:#333;}#mermaid-svg-DgvqiBkXMDIvSZzV .node rect,#mermaid-svg-DgvqiBkXMDIvSZzV .node circle,#mermaid-svg-DgvqiBkXMDIvSZzV .node ellipse,#mermaid-svg-DgvqiBkXMDIvSZzV .node polygon,#mermaid-svg-DgvqiBkXMDIvSZzV .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-DgvqiBkXMDIvSZzV .rough-node .label text,#mermaid-svg-DgvqiBkXMDIvSZzV .node .label text,#mermaid-svg-DgvqiBkXMDIvSZzV .image-shape .label,#mermaid-svg-DgvqiBkXMDIvSZzV .icon-shape .label{text-anchor:middle;}#mermaid-svg-DgvqiBkXMDIvSZzV .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-DgvqiBkXMDIvSZzV .rough-node .label,#mermaid-svg-DgvqiBkXMDIvSZzV .node .label,#mermaid-svg-DgvqiBkXMDIvSZzV .image-shape .label,#mermaid-svg-DgvqiBkXMDIvSZzV .icon-shape .label{text-align:center;}#mermaid-svg-DgvqiBkXMDIvSZzV .node.clickable{cursor:pointer;}#mermaid-svg-DgvqiBkXMDIvSZzV .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-DgvqiBkXMDIvSZzV .arrowheadPath{fill:#333333;}#mermaid-svg-DgvqiBkXMDIvSZzV .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-DgvqiBkXMDIvSZzV .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-DgvqiBkXMDIvSZzV .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-DgvqiBkXMDIvSZzV .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-DgvqiBkXMDIvSZzV .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-DgvqiBkXMDIvSZzV .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-DgvqiBkXMDIvSZzV .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-DgvqiBkXMDIvSZzV .cluster text{fill:#333;}#mermaid-svg-DgvqiBkXMDIvSZzV .cluster span{color:#333;}#mermaid-svg-DgvqiBkXMDIvSZzV div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-DgvqiBkXMDIvSZzV .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-DgvqiBkXMDIvSZzV rect.text{fill:none;stroke-width:0;}#mermaid-svg-DgvqiBkXMDIvSZzV .icon-shape,#mermaid-svg-DgvqiBkXMDIvSZzV .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-DgvqiBkXMDIvSZzV .icon-shape p,#mermaid-svg-DgvqiBkXMDIvSZzV .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-DgvqiBkXMDIvSZzV .icon-shape .label rect,#mermaid-svg-DgvqiBkXMDIvSZzV .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-DgvqiBkXMDIvSZzV .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-DgvqiBkXMDIvSZzV .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-DgvqiBkXMDIvSZzV :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 用户问题
向量化
向量数据库检索
Top-K 最相关片段
拼接到 Context
LLM 生成回答
python
# 写入:文本 → 向量 → 存入数据库(静态知识库和动态记忆都走这套)
embedding = get_embedding("用户偏好使用 Python,喜欢简洁的代码风格")
db.store(user_id="u001", vector=embedding, metadata={"type": "preference", "content": "..."})
# 检索:查询 → 向量 → 最近邻搜索
results = db.search(get_embedding("帮我写一个排序函数"), top_k=3)
两个应用场景
同一套向量检索机制,按数据源分两类------RAG 检索静态知识库,外部记忆检索动态积累:
| 维度 | RAG(静态知识库) | 外部记忆(动态记忆) |
|---|---|---|
| 数据源 | 文档/Wiki/FAQ | 对话历史/用户行为 |
| 更新频率 | 低(定期重新索引) | 高(实时写入) |
| 检索目标 | 找到相关文档片段 | 找到相关历史记忆 |
| 典型应用 | 客服问答、文档分析 | 个性化助手、长期对话 |
检索后如何拼接到 Context
检索到的片段不能简单堆砌,需按模板结构化注入:
[系统指令] 你是一个客服助手,请根据以下参考资料回答用户问题。
[检索结果]
--- 文档 1 (相关度: 0.92) ---
产品 A 支持退货,退货期为购买后 7 天内...
--- 文档 2 (相关度: 0.87) ---
退货流程:1) 提交退货申请 → 2) 审核通过 → 3) 寄回商品...
--- 文档 3 (相关度: 0.83) ---
退款到账时间:3-5 个工作日...
[当前问题] 产品 A 怎么退货?多久能退款?
Top-K 选择策略
| 场景 | Top-K 值 | 说明 |
|---|---|---|
| 精确问答 | 3-5 | 问题明确,少量高质量片段即可 |
| 开放讨论 | 8-12 | 需要多角度信息,适当增加检索量 |
| 代码搜索 | 3-5 | 代码片段较长,K 不宜过大 |
| 事实核查 | 1-3 | 只需最相关的证据即可 |
⚠️ 超预算处理:当检索结果总长度超出 Context 预算时,优先保留相关度最高的片段,或对低相关度片段进行压缩摘要。
常见向量数据库对比
| 数据库 | 特点 | 适用场景 | 是否开源 |
|---|---|---|---|
| ChromaDB | 轻量级,Python 原生,零配置 | 原型开发、小规模项目 | ✅ |
| Pinecone | 全托管,自动扩缩容 | 生产环境、无需运维 | ❌ |
| Milvus | 高性能,支持百万级向量 | 大规模企业应用 | ✅ |
| Weaviate | 支持混合检索(向量+关键词) | 需要精确+语义双检索 | ✅ |
| Qdrant | Rust 实现,低延迟 | 实时性要求高的场景 | ✅ |
💡 选型建议:学习阶段推荐 ChromaDB(零配置,Python 友好);生产环境看规模------小型用 Pinecone(免运维),大规模用 Milvus(高性能开源)。
适用场景
- 知识库问答(产品文档、FAQ、内部 Wiki)
- 长文档分析(书籍、论文、法律文档)
- 个性化助手与长期对话(把用户偏好、历史决策存为外部记忆按需检索)
6.3.2 Token 级压缩
核心思想
检索结果、历史对话、指令拼进 Context 之前,先压掉冗余 token------同样大的窗口能装下更多有效信息,信噪比更高,还能省输入成本。注意它和 6.2.1 的"摘要压缩"不是一回事:摘要压缩是语义级的(把长文缩成短文,会改写),本节讲的 Token 级压缩则是去掉对回答没贡献的冗余 token,尽量不改原意。
两种压缩方式
| 方式 | 做法 | 压缩率 | 是否改原意 |
|---|---|---|---|
| 规则裁剪 | 去重复片段、移除客套与冗余标记(按相关度截断见 6.2.3) | 10-30% | 否 |
| 语义压缩 | 用小模型评估每个 token 对输出的贡献,删掉贡献低的 token(如 LLMLingua 思路) | 2-20× | 轻微 |
python
def compress_context(retrieved_docs, query, max_tokens):
"""检索结果送入 Context 前压缩:去重 + 去冗(截断复用 6.2.3)"""
unique = dedup_by_similarity(retrieved_docs, threshold=0.9) # 去重:语义重叠的只留一条
pruned = [prune_irrelevant(doc, query) for doc in unique] # 去冗:片段内删与 query 无关的句子
return PrioritySelector().select(pruned, query, max_tokens) # 截断:见 6.2.3
💡 压缩 vs 摘要 vs 格式优化 :格式优化(6.2.4)是改表达(
<user>你好</user>→User:你好),摘要压缩(6.2.1)是缩内容(长文→短文),Token 级压缩是删冗余 token(不动语义结构、只去对输出无贡献的部分)。三者互补,可叠加。
适用场景:检索结果冗余高、prompt 接近窗口上限、输入成本敏感(长上下文模型按 token 计费时收益最明显)。
6.3.3 长上下文窗口策略
核心思想
现在的模型上下文窗口已经到 128K--2M(如 Gemini 2M),但"能塞下"不等于"该全塞"。窗口变大没有让 Context 工程过时,反而让"塞什么、不塞什么"的决策更重要。
为什么不无脑全塞
| 问题 | 说明 |
|---|---|
| 成本 | 输入 token 按量计费,每次都全塞 = 每次都贵 |
| Lost in the Middle | 放在中间的信息召回率最低(6.1.3 已讲),全塞反而埋没关键信息 |
| 注意力稀释 | Context 越长,单个 token 分到的注意力越少,关键信息易被忽略 |
| 时效/相关性 | 全塞会把无关历史也带上,干扰当前任务 |
全塞 vs 检索的决策
| 场景 | 窗口占用 | 推荐策略 |
|---|---|---|
| 短文档(<8K token) | <10% 窗口 | 直接全塞,不必检索 |
| 长文档静态分析 | 超窗口 | 分块 RAG 检索 |
| 多轮对话历史 | 持续增长 | 摘要 + 选择性检索(见 6.5) |
| 超长上下文模型(1M 窗口) | 看任务 | 简单 QA 可全塞;复杂推理仍需检索/压缩,避免注意力稀释 |
分批送入(Map-Reduce 风格)
文档远超窗口时,分批送入、各自产出中间结果、再汇总,而不是试图一次塞完:
python
def map_reduce_long_doc(long_doc, chunk_size=8000):
"""超长文档:分批处理 → 中间摘要 → 汇总"""
chunks = split_by_tokens(long_doc, chunk_size)
# Map:每块各自摘要
partial = [llm_generate(f"摘要这块内容:\n{c}") for c in chunks]
# Reduce:汇总所有摘要
return llm_generate(f"综合以下各部分摘要给出最终答案:\n{chr(10).join(partial)}")
💡 一句话:窗口越大,越要克制------Context 工程的核心始终是"放对、放够、放好",不是"放满"。
6.4 记忆机制设计
6.4.1 短期记忆 vs 长期记忆
| 特性 | 短期记忆 | 长期记忆 |
|---|---|---|
| 存储位置 | Context 窗口内 | 外部数据库/文件 |
| 访问速度 | 即时 O(1) | 需检索 O(log n) |
| 容量 | 有限(受 Token 限制) | 几乎无限 |
| 持久性 | 会话结束即消失 | 跨会话保留 |
| 典型内容 | 当前对话、临时变量 | 用户偏好、历史决策 |

💡 类比理解 :短期记忆就像工作台上的工具 ------伸手可取但空间有限;长期记忆就像仓库里的库存------容量大但需要去取。
💡 UserProfile 模式:长期记忆中的用户画像(UserProfile)可在会话开始时注入到短期 Context 中,实现个性化服务。详见 6.5.3 节。
6.4.2 检索策略
长期记忆的检索和 6.2.3 的优先级排序是同一套打分思路 ------相关性、时效性、重要性三维加权。区别在于:记忆库是跨会话积累的,多了两个记忆特有的维度------访问频率 (被检索越多说明越常用)和重要性衰减 (长期不访问的低重要性记忆逐渐淡出)。所以不必重写相似度和时间衰减的实现(向量相似度见 6.3.1,指数衰减见 6.2.3),直接复用 6.2.3 的 PrioritySelector,加上记忆维度:
python
class MemoryRetriever(PrioritySelector):
"""记忆检索:复用 6.2.3 三维打分,加记忆特有的访问频率维度"""
def score(self, mem, query):
base = super().score(mem, query) # 相关性 + 时效 + 重要性
freq = min(mem.get("access_count", 0) / 10, 1.0) # 访问频率归一化
return 0.85 * base + 0.15 * freq # 记忆场景:访问频率占 15%
| 场景 | 相关性 | 时效 | 重要性 | 访问频率 | 说明 |
|---|---|---|---|---|---|
| 客服记忆 | 0.3 | 0.5 | 0.1 | 0.1 | 最新问题最重要 |
| 个性化助手 | 0.3 | 0.2 | 0.3 | 0.2 | 用户偏好(重要性)和历史行为(频率)并重 |
| 项目知识库 | 0.5 | 0.1 | 0.3 | 0.1 | 找到最相关文档最重要 |
💡 不要为记忆单独再造一套打分框架------复用 6.2.3 的三维打分,按场景调权重 + 记忆特有维度即可。记忆库的存储与向量检索机制见 6.3.1。
6.4.3 更新与遗忘
记忆更新策略
#mermaid-svg-A1bW67jdiCEnUR65{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-A1bW67jdiCEnUR65 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-A1bW67jdiCEnUR65 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-A1bW67jdiCEnUR65 .error-icon{fill:#552222;}#mermaid-svg-A1bW67jdiCEnUR65 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-A1bW67jdiCEnUR65 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-A1bW67jdiCEnUR65 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-A1bW67jdiCEnUR65 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-A1bW67jdiCEnUR65 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-A1bW67jdiCEnUR65 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-A1bW67jdiCEnUR65 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-A1bW67jdiCEnUR65 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-A1bW67jdiCEnUR65 .marker.cross{stroke:#333333;}#mermaid-svg-A1bW67jdiCEnUR65 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-A1bW67jdiCEnUR65 p{margin:0;}#mermaid-svg-A1bW67jdiCEnUR65 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-A1bW67jdiCEnUR65 .cluster-label text{fill:#333;}#mermaid-svg-A1bW67jdiCEnUR65 .cluster-label span{color:#333;}#mermaid-svg-A1bW67jdiCEnUR65 .cluster-label span p{background-color:transparent;}#mermaid-svg-A1bW67jdiCEnUR65 .label text,#mermaid-svg-A1bW67jdiCEnUR65 span{fill:#333;color:#333;}#mermaid-svg-A1bW67jdiCEnUR65 .node rect,#mermaid-svg-A1bW67jdiCEnUR65 .node circle,#mermaid-svg-A1bW67jdiCEnUR65 .node ellipse,#mermaid-svg-A1bW67jdiCEnUR65 .node polygon,#mermaid-svg-A1bW67jdiCEnUR65 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-A1bW67jdiCEnUR65 .rough-node .label text,#mermaid-svg-A1bW67jdiCEnUR65 .node .label text,#mermaid-svg-A1bW67jdiCEnUR65 .image-shape .label,#mermaid-svg-A1bW67jdiCEnUR65 .icon-shape .label{text-anchor:middle;}#mermaid-svg-A1bW67jdiCEnUR65 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-A1bW67jdiCEnUR65 .rough-node .label,#mermaid-svg-A1bW67jdiCEnUR65 .node .label,#mermaid-svg-A1bW67jdiCEnUR65 .image-shape .label,#mermaid-svg-A1bW67jdiCEnUR65 .icon-shape .label{text-align:center;}#mermaid-svg-A1bW67jdiCEnUR65 .node.clickable{cursor:pointer;}#mermaid-svg-A1bW67jdiCEnUR65 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-A1bW67jdiCEnUR65 .arrowheadPath{fill:#333333;}#mermaid-svg-A1bW67jdiCEnUR65 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-A1bW67jdiCEnUR65 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-A1bW67jdiCEnUR65 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-A1bW67jdiCEnUR65 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-A1bW67jdiCEnUR65 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-A1bW67jdiCEnUR65 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-A1bW67jdiCEnUR65 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-A1bW67jdiCEnUR65 .cluster text{fill:#333;}#mermaid-svg-A1bW67jdiCEnUR65 .cluster span{color:#333;}#mermaid-svg-A1bW67jdiCEnUR65 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-A1bW67jdiCEnUR65 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-A1bW67jdiCEnUR65 rect.text{fill:none;stroke-width:0;}#mermaid-svg-A1bW67jdiCEnUR65 .icon-shape,#mermaid-svg-A1bW67jdiCEnUR65 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-A1bW67jdiCEnUR65 .icon-shape p,#mermaid-svg-A1bW67jdiCEnUR65 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-A1bW67jdiCEnUR65 .icon-shape .label rect,#mermaid-svg-A1bW67jdiCEnUR65 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-A1bW67jdiCEnUR65 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-A1bW67jdiCEnUR65 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-A1bW67jdiCEnUR65 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 是
否
是
否
新信息到达
是否已存在?
是否冲突?
新增记忆
版本更新
合并信息
标记更新时间
遗忘机制
python
class ForgettingMemory:
"""带遗忘机制的记忆系统"""
def __init__(self, max_capacity: int = 100):
self.memories = []
self.max_capacity = max_capacity
def cleanup(self):
# 容量限制 - 保留重要性最高的
if len(self.memories) > self.max_capacity:
self.memories.sort(key=lambda m: m["importance"])
self.memories = self.memories[-self.max_capacity:] # 保留重要性最高的
# 时间过期 - 移除超过 30 天且低重要性的
cutoff = time.time() - 30 * 24 * 3600
self.memories = [m for m in self.memories if m["timestamp"] > cutoff or m["importance"] > 0.8]
6.5 多轮对话 Context 管理
多轮对话的 Context 管理是 6.2 通用策略的特化------压缩、窗口、优先级排序都用上,只是处理对象从"文档"变成"对话轮次"。本节讲对话场景特有的截断、话题追踪与用户画像。
6.5.1 对话历史截断策略
#mermaid-svg-RGuLbkurVL7Jjm10{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-RGuLbkurVL7Jjm10 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-RGuLbkurVL7Jjm10 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-RGuLbkurVL7Jjm10 .error-icon{fill:#552222;}#mermaid-svg-RGuLbkurVL7Jjm10 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-RGuLbkurVL7Jjm10 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-RGuLbkurVL7Jjm10 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-RGuLbkurVL7Jjm10 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-RGuLbkurVL7Jjm10 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-RGuLbkurVL7Jjm10 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-RGuLbkurVL7Jjm10 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-RGuLbkurVL7Jjm10 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-RGuLbkurVL7Jjm10 .marker.cross{stroke:#333333;}#mermaid-svg-RGuLbkurVL7Jjm10 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-RGuLbkurVL7Jjm10 p{margin:0;}#mermaid-svg-RGuLbkurVL7Jjm10 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-RGuLbkurVL7Jjm10 .cluster-label text{fill:#333;}#mermaid-svg-RGuLbkurVL7Jjm10 .cluster-label span{color:#333;}#mermaid-svg-RGuLbkurVL7Jjm10 .cluster-label span p{background-color:transparent;}#mermaid-svg-RGuLbkurVL7Jjm10 .label text,#mermaid-svg-RGuLbkurVL7Jjm10 span{fill:#333;color:#333;}#mermaid-svg-RGuLbkurVL7Jjm10 .node rect,#mermaid-svg-RGuLbkurVL7Jjm10 .node circle,#mermaid-svg-RGuLbkurVL7Jjm10 .node ellipse,#mermaid-svg-RGuLbkurVL7Jjm10 .node polygon,#mermaid-svg-RGuLbkurVL7Jjm10 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-RGuLbkurVL7Jjm10 .rough-node .label text,#mermaid-svg-RGuLbkurVL7Jjm10 .node .label text,#mermaid-svg-RGuLbkurVL7Jjm10 .image-shape .label,#mermaid-svg-RGuLbkurVL7Jjm10 .icon-shape .label{text-anchor:middle;}#mermaid-svg-RGuLbkurVL7Jjm10 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-RGuLbkurVL7Jjm10 .rough-node .label,#mermaid-svg-RGuLbkurVL7Jjm10 .node .label,#mermaid-svg-RGuLbkurVL7Jjm10 .image-shape .label,#mermaid-svg-RGuLbkurVL7Jjm10 .icon-shape .label{text-align:center;}#mermaid-svg-RGuLbkurVL7Jjm10 .node.clickable{cursor:pointer;}#mermaid-svg-RGuLbkurVL7Jjm10 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-RGuLbkurVL7Jjm10 .arrowheadPath{fill:#333333;}#mermaid-svg-RGuLbkurVL7Jjm10 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-RGuLbkurVL7Jjm10 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-RGuLbkurVL7Jjm10 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-RGuLbkurVL7Jjm10 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-RGuLbkurVL7Jjm10 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-RGuLbkurVL7Jjm10 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-RGuLbkurVL7Jjm10 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-RGuLbkurVL7Jjm10 .cluster text{fill:#333;}#mermaid-svg-RGuLbkurVL7Jjm10 .cluster span{color:#333;}#mermaid-svg-RGuLbkurVL7Jjm10 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-RGuLbkurVL7Jjm10 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-RGuLbkurVL7Jjm10 rect.text{fill:none;stroke-width:0;}#mermaid-svg-RGuLbkurVL7Jjm10 .icon-shape,#mermaid-svg-RGuLbkurVL7Jjm10 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-RGuLbkurVL7Jjm10 .icon-shape p,#mermaid-svg-RGuLbkurVL7Jjm10 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-RGuLbkurVL7Jjm10 .icon-shape .label rect,#mermaid-svg-RGuLbkurVL7Jjm10 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-RGuLbkurVL7Jjm10 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-RGuLbkurVL7Jjm10 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-RGuLbkurVL7Jjm10 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 未超限
超限
新对话轮次
总长度检查
直接追加
截断策略
固定轮次保留
智能压缩
保留最近 N 轮
摘要替换
构建 Context
python
class ConversationManager:
"""多轮对话管理器"""
def __init__(self, max_tokens: int = 8000, target_tokens: int = 6000):
self.max_tokens = max_tokens
self.target_tokens = target_tokens
self.history = []
def add_turn(self, user_msg: str, assistant_msg: str):
self.history.extend([
{"role": "user", "content": user_msg},
{"role": "assistant", "content": assistant_msg}
])
if self._count_tokens() > self.target_tokens:
self._compress_history()
def _compress_history(self):
current = self._count_tokens()
if current > self.max_tokens * 0.9:
# 直接丢弃最早轮次
self.history = [m for m in self.history if m["role"] == "system"] + self.history[2:]
elif len(self.history) > 4:
# 摘要早期对话
recent = self.history[-4:]
early_text = "\n".join([m["content"] for m in self.history[:-4]])
summary = llm_generate(f"摘要以下对话:\n{early_text}")
self.history = [{"role": "system", "content": f"[摘要]\n{summary}"}] + recent
6.5.2 话题追踪
话题追踪是识别对话中话题切换、保存旧话题状态、加载新话题 Context 的机制。
阈值选择
transition_threshold 是判断"话题是否切换"的相似度阈值。
| 阈值 | 效果 | 适用场景 |
|---|---|---|
| 0.3-0.4 | 宽松,容易切换 | 闲聊、多任务切换频繁 |
| 0.5-0.6 | 适中 | 大多数场景推荐 |
| 0.7-0.8 | 严格,不容易切换 | 深度讨论、技术分析 |
💡 阈值太低会导致正常追问被误判为话题切换,阈值太高会忽略真正的话题切换。建议从 0.6 开始,根据实际对话数据微调。
python
class TopicTracker:
"""话题追踪器"""
def __init__(self, transition_threshold: float = 0.6):
self.current_topic = None
self.topics = {}
self.transition_threshold = transition_threshold
def detect_topic_change(self, new_message: str) -> bool:
if self.current_topic is None:
return False
current_context = self.topics[self.current_topic]["context"]
similarity = cosine_similarity(get_embedding(new_message), get_embedding(current_context))
return similarity < self.transition_threshold
def switch_topic(self, new_topic: str):
"""切换话题:保存旧话题 → 加载新话题"""
if self.current_topic:
self._save_topic_state(self.current_topic)
self.current_topic = new_topic
if new_topic not in self.topics:
self.topics[new_topic] = {"messages": [], "context": ""}
def _save_topic_state(self, topic: str):
"""保存旧话题的摘要到长期记忆"""
msgs = self.topics[topic]["messages"]
if msgs:
summary = llm_generate(f"摘要以下关于'{topic}'的对话:\n{msgs}")
self.topics[topic]["context"] = summary
话题切换后的 Context 处理
- 保存旧话题:将旧话题对话摘要后存入长期记忆
- 轻装切换:清空短期 Context 中与旧话题无关的内容
- 加载新背景:如新话题有历史记忆,检索并注入
多话题并行
用户在讨论 A 时中间穿插了一个 B 的问题,说完 B 又回到 A。处理方式是用话题栈(而非单一话题):
python
# 多话题并行的简化处理
topic_stack = ["编程讨论"] # 当前栈
# 用户穿插问天气 → push 新话题
topic_stack.append("天气查询") # ["编程讨论", "天气查询"]
# 天气回答完 → pop 回旧话题
topic_stack.pop() # ["编程讨论"]

6.5.3 用户画像维护
用户画像(UserProfile)是长期记忆的重要组成部分,用于在会话中提供个性化服务。
| 维度 | 内容 | 示例 |
|---|---|---|
| 基本信息 | 职业、地点、语言偏好 | "软件工程师,成都" |
| 技能水平 | 专业知识、技术栈、经验 | "Python 高级,机器学习中级" |
| 交互偏好 | 回答长度、表达风格 | "偏好简洁,技术导向" |
| 兴趣领域 | 关注主题、项目类型 | "AI 应用、RAG 系统" |
python
class UserProfile:
"""用户画像管理"""
def __init__(self, user_id: str):
self.user_id = user_id
self.profile = {"basic_info": {}, "skill_level": {}, "preferences": {}}
def update_from_conversation(self, conversation: list):
prompt = f"分析对话提取用户画像:{conversation[-20:]}\n输出 JSON 格式"
updates = json.loads(llm_generate(prompt))
self._merge_updates(updates)
def get_context_injection(self) -> str:
parts = []
if self.profile["basic_info"].get("profession"):
parts.append(f"用户职业:{self.profile['basic_info']['profession']}")
return "\n".join(parts)
6.6 实战案例
6.6.1 完整的对话管理系统
python
class DialogContextManager:
"""完整的对话 Context 管理系统"""
def __init__(self, max_tokens: int = 8000, user_id: str = None):
self.max_tokens = max_tokens
self.messages = []
self.user_profile = UserProfile(user_id) if user_id else None
def add_message(self, role: str, content: str):
if role == "user" and self.user_profile:
self.user_profile.update_from_conversation(self.messages[-10:])
self.messages.append({
"role": role, "content": content,
"timestamp": time.time(), "tokens": estimate_tokens(content)
})
self._manage_context_length()
def _manage_context_length(self):
total = self._count_total_tokens()
if total > self.max_tokens * 0.9:
self._truncate_oldest()
elif total > self.max_tokens * 0.7:
self._compress_smart()
def _compress_smart(self):
system_msg = [m for m in self.messages if m["role"] == "system"]
recent = self.messages[-6:]
middle = self.messages[len(system_msg):-6]
if middle:
summary = llm_generate(f"用 100 字摘要:\n{[m['content'] for m in middle]}")
self.messages = system_msg + [{"role": "system", "content": f"[摘要]\n{summary}"}] + recent
def _truncate_oldest(self):
system_msg = [m for m in self.messages if m["role"] == "system"]
self.messages = system_msg + self.messages[-8:]
6.6.2 实战场景:AI 编程助手
**场景需求:**记住用户编程偏好、维护项目上下文、支持跨会话继续、处理超长代码文件。
Token 预算分配(8K 总预算)
| 内容 | Token 预算 | 说明 |
|---|---|---|
| 系统指令 | 500 | 角色、约束、输出格式 |
| 用户画像 | 300 | 编程偏好、技能水平 |
| 当前任务 | 1000 | 任务描述、验收标准 |
| 活动文件 | 4000 | 当前编辑的代码文件 |
| 对话历史 | 2000 | 最近 5-8 轮对话 |
| 预留输出 | 200 | 生成 Response |
超长代码处理
python
def handle_long_code_file(file_path: str, max_tokens: int = 4000, current_task: str = "") -> str:
"""处理超长代码文件"""
with open(file_path, 'r') as f:
full_code = f.read()
if estimate_tokens(full_code) > max_tokens:
# 提取与任务相关的代码片段
prompt = f"从代码中提取与'{current_task}'相关的部分,保留关键 import 和函数定义"
return llm_generate(f"{prompt}\n\n{full_code[:10000]}")
return full_code

6.7 常见误区
| 误区 | 错误示例 | 正确做法 | 影响 |
|---|---|---|---|
| 过度堆砌 | 把能塞的所有内容都放进 Context | 按优先级选择,保持精简 | Context 膨胀,关键信息被稀释 |
| 忽视结构 | 大段连续文字,无标记分隔 | 使用标题、列表、标记清晰分隔 | 模型难以定位关键信息 |
| 历史全留 | 保留所有历史对话不截断 | 智能压缩 + 选择性保留 | Token 浪费,响应变慢 |
| 重要信息放中间 | 关键指令埋在 Context 中部 | 放在开头或结尾 | 受 U 型注意力影响被忽略 |
| 忽略输出空间 | Context 占满 128K,不留输出空间 | 预留 20-30% 给输出 | 生成被截断 |
| 重复背景 | 每轮都重复相同背景说明 | 只说一次,后续引用 | Token 浪费 |
| Context 污染 | 注入无关信息或用户输入覆盖指令 | 用标签隔离,输入验证 | 模型被误导或注入攻击 |
#mermaid-svg-vfsjJqF2U9J5xtTR{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-vfsjJqF2U9J5xtTR .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-vfsjJqF2U9J5xtTR .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-vfsjJqF2U9J5xtTR .error-icon{fill:#552222;}#mermaid-svg-vfsjJqF2U9J5xtTR .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-vfsjJqF2U9J5xtTR .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-vfsjJqF2U9J5xtTR .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-vfsjJqF2U9J5xtTR .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-vfsjJqF2U9J5xtTR .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-vfsjJqF2U9J5xtTR .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-vfsjJqF2U9J5xtTR .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-vfsjJqF2U9J5xtTR .marker{fill:#333333;stroke:#333333;}#mermaid-svg-vfsjJqF2U9J5xtTR .marker.cross{stroke:#333333;}#mermaid-svg-vfsjJqF2U9J5xtTR svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-vfsjJqF2U9J5xtTR p{margin:0;}#mermaid-svg-vfsjJqF2U9J5xtTR .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-vfsjJqF2U9J5xtTR .cluster-label text{fill:#333;}#mermaid-svg-vfsjJqF2U9J5xtTR .cluster-label span{color:#333;}#mermaid-svg-vfsjJqF2U9J5xtTR .cluster-label span p{background-color:transparent;}#mermaid-svg-vfsjJqF2U9J5xtTR .label text,#mermaid-svg-vfsjJqF2U9J5xtTR span{fill:#333;color:#333;}#mermaid-svg-vfsjJqF2U9J5xtTR .node rect,#mermaid-svg-vfsjJqF2U9J5xtTR .node circle,#mermaid-svg-vfsjJqF2U9J5xtTR .node ellipse,#mermaid-svg-vfsjJqF2U9J5xtTR .node polygon,#mermaid-svg-vfsjJqF2U9J5xtTR .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-vfsjJqF2U9J5xtTR .rough-node .label text,#mermaid-svg-vfsjJqF2U9J5xtTR .node .label text,#mermaid-svg-vfsjJqF2U9J5xtTR .image-shape .label,#mermaid-svg-vfsjJqF2U9J5xtTR .icon-shape .label{text-anchor:middle;}#mermaid-svg-vfsjJqF2U9J5xtTR .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-vfsjJqF2U9J5xtTR .rough-node .label,#mermaid-svg-vfsjJqF2U9J5xtTR .node .label,#mermaid-svg-vfsjJqF2U9J5xtTR .image-shape .label,#mermaid-svg-vfsjJqF2U9J5xtTR .icon-shape .label{text-align:center;}#mermaid-svg-vfsjJqF2U9J5xtTR .node.clickable{cursor:pointer;}#mermaid-svg-vfsjJqF2U9J5xtTR .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-vfsjJqF2U9J5xtTR .arrowheadPath{fill:#333333;}#mermaid-svg-vfsjJqF2U9J5xtTR .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-vfsjJqF2U9J5xtTR .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-vfsjJqF2U9J5xtTR .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-vfsjJqF2U9J5xtTR .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-vfsjJqF2U9J5xtTR .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-vfsjJqF2U9J5xtTR .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-vfsjJqF2U9J5xtTR .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-vfsjJqF2U9J5xtTR .cluster text{fill:#333;}#mermaid-svg-vfsjJqF2U9J5xtTR .cluster span{color:#333;}#mermaid-svg-vfsjJqF2U9J5xtTR div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-vfsjJqF2U9J5xtTR .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-vfsjJqF2U9J5xtTR rect.text{fill:none;stroke-width:0;}#mermaid-svg-vfsjJqF2U9J5xtTR .icon-shape,#mermaid-svg-vfsjJqF2U9J5xtTR .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-vfsjJqF2U9J5xtTR .icon-shape p,#mermaid-svg-vfsjJqF2U9J5xtTR .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-vfsjJqF2U9J5xtTR .icon-shape .label rect,#mermaid-svg-vfsjJqF2U9J5xtTR .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-vfsjJqF2U9J5xtTR .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-vfsjJqF2U9J5xtTR .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-vfsjJqF2U9J5xtTR :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} Context 管理误区
信息组织
长度控制
位置策略
❌ 无结构文本
❌ 过度堆砌
❌ 中间放重点
✅ 清晰标记分隔
✅ 优先级选择
✅ 两端放重点
本章小结
- Context 是 LLM 生成响应时的所有输入信息总和,包括系统提示词、用户输入、历史对话、外部知识、工具结果
- 各主流模型 Context 窗口在 128K-200K 范围,需预留 20-30% 给输出
- 注意力机制导致 U 型分布(Lost in the Middle),重要信息应放在 Context 两端
- Context 优化四大策略:信息压缩 (摘要/提取/分层)、窗口管理 (固定分块/重叠窗口)、优先级排序 (相关性/时效性/重要性三维打分)、格式优化(移除冗余/结构化)
- 高级 Context 技术:检索增强与外部记忆(同一套向量检索机制覆盖静态知识库 RAG 与动态记忆,注意 Top-K 选择、Context 拼接模板、向量库选型)、Token 级压缩(去冗余 token,区别于 6.2.1 语义级摘要)、长上下文窗口策略(大窗口下"全塞 vs 检索"的决策、分批送入)
- 记忆系统分短期(Context 内,即时访问)和长期(外部数据库,按需检索),长期记忆的检索复用 6.2.3 的三维打分框架,叠加记忆特有的访问频率维度
- 多轮对话管理核心:历史截断(固定轮次/智能压缩)、话题追踪(阈值选择+多话题并行)、用户画像维护
- 规避常见误区:避免过度堆砌、重视结构化、重要信息不放中间、预留输出空间、避免重复背景